1

I understand that in Angular the following two lines are functionally the same

Property and Event binding

<input type="text" [value]="customerName" (input)="customerName= $event.target.value" />

Two-Way Data Binding

<input type="text" [(ngModel)]="customerName' />

What confuses me is how Angular knows, with Two-Way Data Binding, to bind to the input event of the input elementy rather than any of the other events that the input element supports?

In the first example the code is specifically defining which event to bind to (the "input" event), but not in the second example. How does Angular choose the event to bind to?

1
  • 1
    Input directive uses input event by default - docs Commented Oct 27, 2019 at 6:16

2 Answers 2

5

<input [(ngModel)]="customerName"> is a short form of <input [ngModel]="customerName" (ngModelChange)="customerName = $event">. This is a convention in Angular and also works with your own custom defined directives.

The NgModelDirective (bound by [ngModel]) provides @Input('ngModel') model: any; and @Output('ngModelChange') update = new EventEmitter();.

I can recommend to take a look here at the docs and also at the source to get a better understanding.

Sign up to request clarification or add additional context in comments.

Comments

1

The two way data binding isn't really binding to the input event, it's the way the ngModel directive works: It passes any changes in the value of the given object to the input element and vice versa.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.