【问题标题】:Difference between binding the attributes with [attr.attributeName] and [attributeName] in Angular2在 Angular2 中将属性与 [attr.attributeName] 和 [attributeName] 绑定的区别
【发布时间】:2017-08-16 12:42:47
【问题描述】:

我是 Angular2 的新手。当 iam 绑定属性时,我以前是按以下方式进行的。

示例 1:

  <input type="number" [max]="variableName">

示例2:

<select [(ngModel)]="selectedItem">
  <option *ngFor="let item of itemList" [value]="item.value" [selected]="selectedItem==item.value">{{item.name}}</option>
</select>

这些绑定有时会失败。

然后我使用以下语法通过后缀 attr 来绑定属性。为它。

示例 1:

<input type="number" [attr.max]="variableName">

示例 2:

 <select [(ngModel)]="selectedItem">
      <option *ngFor="let item of itemList" [value]="item.value" [attr.selected]="selectedItem==item.value">{{item.name}}</option>
    </select>

这些语法曾经有时像魅力一样工作。

请帮助我了解这两个绑定 [attributename][attr.attributeName] 之间的区别,以及使用这些特定语法的重要性。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    这是属性绑定

    [selected]="selectedItem==item.value"
    

    这是属性绑定

    [attr.selected]="selectedItem==item.value"
    

    有关属性和属性之间的区别,另请参阅What is the difference between attribute and property?

    只有当元素实际上有一个具有该名称的属性时,属性绑定才有效。某些属性会自动反映到属性中。

    Attribute 只是将具有该名称的属性添加到 DOM 元素。已知属性由元素(以及 Angular 组件的@Input()s)读取。 自定义属性只是添加到 DOM 中,不被元素处理。

    【讨论】:

    • 感谢您提供有用的信息。
    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2016-09-17
    • 2015-09-28
    • 2016-12-04
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多