beNerd
beNerd

Reputation: 3374

understanding property binding in angular 2

I have a naive question. Say I have a input element defined like the below:

<input [(ngModel)]=model.username name="username" id="username">

The above essentially means that there is now a PROPERTY called ngModel defined on the input element which in turn is binded to model.username. All good so far.

Now just for the learning purpose, I access the input element like so:

let input = document.getElementbyId('username');

And then try to inspect something like input.ngModel...boom...there is no such property!

What I am missing here?

Upvotes: 1

Views: 172

Answers (2)

anonym
anonym

Reputation: 4840

[(ngModel)] provides two-way data-binding by binding to the value.

Property binding provides one-way data binding from data source to view target. Some examples of property binding are:

<input [disabled]="true">
<input [value]="{5 : 'ifSomeCondition()'}"
<input [attr.type]="{'text' : typeIsText()}"

Upvotes: 0

yurzui
yurzui

Reputation: 214007

According to documentation https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-target

Element properties may be the more common targets, but Angular looks first to see if the name is a property of a known directive, as it is in the following example:

<div [ngClass]="classes">[ngClass] binding to the classes property</div>

Technically, Angular is matching the name to a directive input, one of the property names listed in the directive's inputs array or a property decorated with @Input(). Such inputs map to the directive's own properties.

If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error.

So in your case angular found NgModel directive with @Input('ngModel') model: any;

https://github.com/angular/angular/blob/2.4.8/modules/%40angular/forms/src/directives/ng_model.ts#L112

Upvotes: 2

Related Questions