Pravin Tukadiya
Pravin Tukadiya

Reputation: 487

how update model value when input value is changed in Angularjs2

I want to change model value from input tag but I don't know how to do it in best way.

here is my code that I have done for that.

<div *ngFor='let l of list'>
    <input #temp [value]='l.test' (blur)='l.test=temp.value'/>
    <span (click)='check(l,temp.value)'></span>
<div>

angular code

check(l,temp:string)
{
   console.log(l.test);
   console.log(temp);
}

I want to do this without a blur event. please suggest me any better way to do this.

Upvotes: 2

Views: 1624

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136124

Use can [(ngModel)] on the field, that would provide you two way binding on field, as soon as you type in something it would change the l.test value of particular element from an array.

Markup

<div *ngFor='let l of list'>
    <input [(ngModel)]='l.test'/>
<div>

Since Angular 2 rc-5, to make ngModel two way binding working you have import FormsModule in your @NgModule

import { FormsModule } from '@angular/forms';
///..other imports

@NgModule({
  imports:      [ BrowserModule, FormsModule ], //< added FormsModule here
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

You could refer this answer to know how to use two way binding in Angular 2.

Plunkr here

Upvotes: 3

Related Questions