属性绑定与属性插值

属性绑定与属性插值

问题描述:

我已经阅读了一篇有关属性和属性绑定之间差异的文章.据我了解,大多数时候,Angular2更喜欢属性绑定, 因为在每次更改数据后,都会更新DOM. (如果我弄错了,请纠正我.)

I have read an article about difference between property and attribute bindings. From what I understood, most of the time, Angular2 prefers property bindings, because after each change in data, the DOM would be updated. (If I am mistaken, please correct me).

我有一个自定义组件,并从父组件中使用它.在其中,我有一个名为truevalue@Input.当我通过属性绑定从父级启动truevalue时,它不会更改.我使用了以下代码:

I have a custom component and use it from the parent component. In it, I have an @Input named truevalue. when I initiate truevalue from the parent via property binding, sometimes, it does not change. I used following code:

<my-checkbox [(ngModel)]="chkItems" [disabled]="!editMode" [trueValue]="Y"></my-checkbox>

如果我将true"1"发送到trueValue,则可以使用,但是如果我发送"Y""YES",则不能使用.所以我被迫使用属性绑定.我不知道是什么问题.

If I send true or "1" into trueValue it works, but If I send "Y" or "YES", it does not work. So I am forced to use attribute binding. I don't know what is the problem.

我将其更改为以下内容:

I have changed it, into the following:

<my-checkbox [(ngModel)]="chkItems" [disabled]="!editMode" trueValue="Y"></my-checkbox>

预先感谢

属性绑定

[trueValue]="..."

计算表达式"..."并分配值

"true"取值为true "Y"是未知的. TypeScript中没有内部Y值,而组件类实例中也没有属性,这是模板绑定的范围. 在这种情况下,您会想要

"true" evaluates to the value true "Y" is unknown. There is no internal Y value in TypeScript and no property in the component class instance, which is the scope of template binding. In this case you would want

[trueValue]="'Y'"

请注意使Y成为字符串的其他引号.

Note the additional quotes to make Y a string.

普通属性也分配给输入

trueValue="Y"

是没有任何Angular2绑定的纯HTML,并且属性值始终是字符串.因此,这将分配字符串Y.

is plain HTML without any Angular2 binding and attribute values are always strings. Therefore this would assign the string Y.

另一种方法是字符串插值

Another way is string interpolation

trueValue="{{true}}"

将分配值"true"(作为字符串),因为带有{{...}}的表达式将被求值,然后在传递给输入之前转换为字符串. 不能用于绑定字符串以外的其他值.

would assign the value "true" (as string) because the expression withing {{...}} would be evaluated and then converted to a string before passed to the input. This can't be used to bind other values than strings.

要显式绑定到属性而不是属性,可以使用 (除了trueValue="Y"会创建属性,但不执行任何评估)

To explicitly bind to an attribute instead of a property you can use (besides trueValue="Y" which creates an attribute but doesn't do any evaluation)

[attr.trueValue]="'Y'"

attr.trueValue="{{'Y'}}"

如果要使用trueValue属性通过CSS选择器寻址元素,则

属性绑定会很有帮助.

Attribute binding is helpful if you want to use the trueValue attribute to address the element with CSS selectors.