typescript 如何将输入标签的 ngModel 值获取到 angularjs4 中的组件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46359028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:54:50  来源:igfitidea点击:

How to get ngModel value of input tag into a component in angularjs4?

angulartypescriptcomponentsangular-cli

提问by srujana

I am new to angularjs4. I am working on angular-cli.Here I need to get the value of a ngModel value of input tag in my component.How can I get that value entered in input field?By using that value I need to write a filter for displaying searched data on my page.How can I Implement this one in angular4?. Here is my app.component.html and app.component.ts files:

我是 angularjs4 的新手。我正在处理 angular-cli。在这里我需要获取组件中输入标签的 ngModel 值的值。如何在输入字段中输入该值?通过使用该值,我需要编写一个过滤器来显示搜索我页面上的数据。如何在 angular4 中实现这个?。这是我的 app.component.html 和 app.component.ts 文件:

import {
    Component
} from '@angular/core';
import {
    Http,
    Response,
    Headers,
    RequestOptions
} from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    productsList = '';
    show: boolean;
    hide: boolean;
    listBtn: boolean;
    gridBtn: boolean;
    values = '';

    onKey(event: any) { // without type info
        this.values += event.target.value;
        console.log("value " + this.values);
    }
    listView() {
        this.gridBtn = true;
        this.show = true;
        this.hide = false;
        this.listBtn = false;
    }
    gridView() {
        this.listBtn = true;
        this.gridBtn = false;
        this.show = false;
        this.hide = true;

    }
    constructor(private http: Http) {
        this.show = false;
        this.hide = true;
        this.show = false;
        this.listBtn = true;
        this.gridBtn = false;
        this.getData();
    }
    createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' +
            btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
        headers.append("Content-Type", "application/x-www-form-urlencoded");
    }
    getData() {
        console.log('hellooo');
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(' https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products', {
            headers: headers
        })
            .subscribe(res => {
                const products = res.json();
                console.log(products);
                this.productsList = products;
                console.log(this.productsList);
            })


    }

}

HTML

HTML

<div class="container" align="center">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
            <div class="input-group stylish-input-group">
                <input type="text" class="form-control" placeholder="Let's find your product....." (keyup)="onKey($event)">
                <span class="input-group-addon">
                    <button type="submit">
                        <span class="glyphicon glyphicon-search"></span>
                    </button>
                </span>
            </div>
        </div>
    </div>
    <br>
</div>


<br>
<div *ngIf="show">
    <ul class="list-group">
        <li class="list-group-item" *ngFor="let data of productsList">
            <img src="{{data.images[0].src}}" alt="image" width="auto" height="200px">
            <span>{{data.name}}</span>
            <span>{{data.regular_price}}</span>
        </li>
    </ul>
</div>

回答by Harunur Rashid

1.If you want one way data binding (Component to HTML), use -

1.如果您想要一种方式数据绑定(组件到 HTML),请使用 -

<input [ngModel]="variable">

<input [ngModel]="variable">

2.If you want two way data binding (Component to HTML and vice versa), use -

2.如果你想要两种方式的数据绑定(组件到 HTML,反之亦然),使用 -

<input [(ngModel)]="variable">

<input [(ngModel)]="variable">

3.If you want to work with the data changed in input field in html while working with one way data binding, you have to use (ngModelChange) as below :

3.如果您想在使用单向数据绑定的同时处理 html 中输入字段中更改的数据,则必须使用 (ngModelChange) 如下:

<input [ngModel]="variable"(ngModelChange)="function_to_fire_on_model_change($event)">

<input [ngModel]="variable"(ngModelChange)="function_to_fire_on_model_change($event)">

回答by Vega

UPDATE:

更新:

If you want to get the input value, but without ngModel (as in your snipet you don't use it), you can get as this:

如果您想获取输入值,但没有 ngModel(如在您的 snipet 中您不使用它),您可以这样获得:

 <input type="text" #input class="form-control" placeholder="Let's find your product....." (keyup)="onKey($event, input.value)">

onKey(event, newValue){
  console.log(newValue);
  console.log(event.key)
}



通常,模式是:

HTML

HTML

<input [(ngModel)]="yourModel" ....> 

or

或者

<input [ngModel]="yourModel" (ngModelChange)="doSomething($event)"....> 

Typescript:

打字稿:

yourModel:any;
....
doSomething(event){
   console.log(event) // input value is logged
}

Here any changes in the input will update the ngModel as it's two-way bound.

这里输入的任何更改都会更新 ngModel,因为它是双向的。

回答by Sibiraj

<input [(ngModel)]="name"> // two way data binding

<input [(ngModel)]="name" (ngModelChange)="change()">  // two way data binding with onchange property

<input [ngModel]="name"> // one way data binding

In TS

在 TS

name: any

Check here for an example https://stackblitz.com/edit/angular-pmatzc

在此处查看示例https://stackblitz.com/edit/angular-pmatzc

回答by abin peter

you can use the following line in the template

您可以在模板中使用以下行

<input type="text" [(ngModel)]="username" name="username" class="form-control" placeholder="username"  >

and in component.ts file you can access the element by this.username

在 component.ts 文件中,您可以通过 this.username 访问该元素