two way data binding in angular 2

2019-09-11 19:51发布

问题:

I am quiet recent to angular 2 and was bumping my head around two way data binding. Here is the confusion:

  <input  (input)="username = $event.target.value" id="testing">
  <p>{{username}}</p>

This serves the purpose well. It already seems to be two way data binded. I can access username inside the component and the value property of the input element is updated as well. Why do i need [ ] at all then? What is the two way binding here? what goes inside the component and what comes out of the component.

Disclaimer: I know it's a very naive and seemingly stupid question :|

回答1:

As i understand write like you did:

(input)="username = $event.target.value" 

is the same as:

  [(input)]="username"

So they're both 2 way data binding

if you want only one way:

(input)="username"


https://angular.io/docs/ts/latest/guide/template-syntax.html


回答2:

Angular 2 data binding is explained here.

When you write in the input you execute: "username = $event.target.value", wich assigns to the variable user the value you enter.

That means that the following html does the same:

  • [(ngModel)]="username"
  • [username]="username" (input)="updateUserName()"
  • (input)="username = $event.target.value" and {{userName}}