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

37,967

Solution 1

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

<input [ngModel]="variable">

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

<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 :

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

Solution 2

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:

 <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)
}


Usually, the pattern would be:

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.

Solution 3

If ngForm is used, all the input fields which have [(ngModel)]="" must have an attribute name with a value:

<input [(ngModel)]="firstname" name="something">

Solution 4

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

Solution 5

<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

name: any

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

Share:
37,967
srujana
Author by

srujana

Iam a practical person with positive nature.Iam good at programming.Iam proficient in C-language.I have knowledge on basics of Java,C++,html,CSS,Javascript.

Updated on April 16, 2021

Comments

  • srujana
    srujana about 3 years

    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:

    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

    <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>
    
  • srujana
    srujana over 6 years
    how I can get that value?
  • Vega
    Vega over 6 years
    By initialising the property of the class binded to the input
  • srujana
    srujana over 6 years
    Is there any need to import ngModel module to app.module.ts?
  • Vega
    Vega over 6 years
    You have to define the class property to bind to the ngModel, it's not created by Angular by default
  • Vega
    Vega over 4 years
    I think my answer covered all cases, while the other answer just repeated. At least, did this help you?