简体   繁体   English

了解角度2中的属性绑定

[英]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. 以上本质上意味着,现在在输入元素上定义了一个名为ngModel的属性,该属性又绑定到model.username。 All good so far. 到目前为止一切都很好。

Now just for the learning purpose, I access the input element like so: 现在仅出于学习目的,我像这样访问input元素:

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

And then try to inspect something like input.ngModel ...boom...there is no such property! 然后尝试检查诸如input.ngModel ... boom之类的东西,没有这样的属性!

What I am missing here? 我在这里想念的是什么?

According to documentation https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-target 根据文档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: 元素属性可能是更常见的目标,但是Angular首先查看名称是否是已知指令的属性,如以下示例所示:

<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(). 从技术上讲,Angular会将名称与指令输入匹配,该指令输入是指令的输入数组中列出的属性名称之一,还是用@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. 如果名称不匹配已知指令或元素的属性,Angular将报告“未知指令”错误。

So in your case angular found NgModel directive with @Input('ngModel') model: any; 因此,在您的情况下,使用@Input('ngModel') model: any;找到NgModel指令@Input('ngModel') model: any;

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

[(ngModel)] provides two-way data-binding by binding to the value. [(ngModel)]通过绑定到值来提供two-way data-binding

Property binding provides one-way data binding from data source to view target. 属性绑定提供从数据源到视图目标one-way data binding Some examples of property binding are: 属性绑定的一些示例是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM