绑定目标link
数据绑定的目标是 DOM 中的某些东西。 这个目标可能是(元素 | 组件 | 指令的)property、(元素 | 组件 | 指令的)事件,或(极少数情况下) attribute 名。 下面是的汇总表:
绑定类型 |
目标 |
范例 |
---|---|---|
属性 |
元素的 property |
src/app/app.component.html content_copy |
事件 |
元素的事件 |
src/app/app.component.html content_copy |
双向 |
事件与 property |
src/app/app.component.html content_copy |
Attribute |
attribute(例外情况) |
src/app/app.component.html content_copy |
CSS 类 |
|
src/app/app.component.html content_copy |
样式 |
|
src/app/app.component.html content_copy |
放开眼界,来看看每种绑定类型的具体情况。
单向输入
人们经常把属性绑定描述成单向数据绑定,因为值的流动是单向的,从组件的数据属性流动到目标元素的属性。
People often describe property binding as one-way data binding because it flows a value in one direction, from a component's data property into a target element property.
不能使用属性绑定来从目标元素拉取值,也不能绑定到目标元素的属性来读取它。只能设置它。
也不能使用属性 绑定 来调用目标元素上的方法。
如果这个元素触发了事件,可以通过事件绑定来监听它们。
如果必须读取目标元素上的属性或调用它的某个方法,得用另一种技术。 参见 API 参考手册中的 ViewChild和 ContentChild。
,Angular 数据绑定对危险 HTML 有防备。 在显示它们之前,它对内容先进行消毒。 不管是插值表达式还是属性绑定,都不会允许带有 script 标签的 HTML 泄漏到浏览器中。
SRC /应用程序/ app.component.html
content_copy<!--
Angular generates warnings for these two lines as it sanitizes them
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
-->
<p><span>"{{evilTitle}}" is the <i>interpolated</i> evil title.</span></p>
<p>"<span [innerHTML]="evilTitle"></span>" is the <i>property bound</i> evil title.</p>
插值表达式处理 script 标签与属性绑定有所不同,但是二者都只渲染没有危害的内容。
attribute 绑定
可以通过attribute 绑定来直接设置 attribute 的值。
这是“绑定到目标属性 (property)”这条规则中唯一的例外。这是唯一的能创建和设置 attribute 的绑定形式。
本章中,通篇都在说通过属性绑定来设置元素的属性总是好于用字符串设置 attribute。为什么 Angular 还提供了 attribute 绑定呢?
因为当元素没有属性可绑的时候,就必须使用 attribute 绑定。
考虑 ARIA, SVG 和 table 中的 colspan/rowspan 等 attribute。 它们是纯粹的 attribute,没有对应的属性可供绑定。
如果想写出类似下面这样的东西,就会暴露出痛点了:
content_copy<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
会得到这个错误:
content_copyTemplate parse errors:
Can't bind to 'colspan' since it isn't a known native property
正如提示中所说,<td>
元素没有 colspan
属性。 但是插值表达式和属性绑定只能设置属性,不能设置 attribute。
你需要 attribute 绑定来创建和绑定到这样的 attribute。
attribute 绑定的语法与属性绑定类似。 但方括号中的部分不是元素的属性名,而是由attr
前缀,一个点 (.
) 和 attribute 的名字组成。 可以通过值为字符串的表达式来设置 attribute 的值。
这里把 [attr.colspan]
绑定到一个计算值:
SRC /应用程序/ app.component.html
content_copy<table border=1>
<!-- expression calculates colspan=2 -->
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
<!-- ERROR: There is no `colspan` property to set!
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
-->
<tr><td>Five</td><td>Six</td></tr>
</table>
下一节: CSS类绑定