Davey_31
Davey_31

Reputation: 89

ngModel vs keyup/down

while learning angular2, came across these two ways to read value from input field as below,

<input type="text"[(ngModel)]="pname"> // I can read the value from --> pname
<input type="text" (keyup)="addvalue($event)"> // I can check for enter press and read text

For ex, if I want to write a ToDo app and ask user to enter the list in input field, post clicking Add button, could add it in list

keyup will trigger the method for each keypress, won't it affect the performance?

please explain the scenarios when to use [(ngModel)] and keyup

Upvotes: 1

Views: 3509

Answers (2)

CharanRoot
CharanRoot

Reputation: 6325

you can use <input type="text"[(ngModel)]="pname">

angular will internally convert [(ngModel)] into

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

The property binding [ngModel] takes care of updating the underlying input DOM element. The event binding (ngModelChange) notifies the component calss(.ts File) when there was a change in the DOM

Upvotes: 0

DeborahK
DeborahK

Reputation: 60528

Use ngModel when you want two way binding: setting a default value and getting any changes to that value.

Use keyup when you what to watch the keys the user types, such as watching for entry of a return key.

Upvotes: 1

Related Questions