Mar*_*rgh 16 data-binding property-binding angular
我注意到没有括号可以绑定东西.有什么不同?
打字稿:
import { Component, Input } from '@angular/core';
@Component( {
selector: 'my-comp',
templateUrl: `
input is {{foo}}
`
})
export class myComponent {
@Input() public foo: string;
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
HTML:
情况1
<my-comp [foo]="bar"></my-comp>
Run Code Online (Sandbox Code Playgroud)
案例2
<my-comp foo="bar"></my-comp>
Run Code Online (Sandbox Code Playgroud)
Nad*_*ine 19
一般来说,我们可以说只有当我们有一个固定的字符串属性时才应该使用没有括号的绑定:
来自文档:
如果满足以下所有条件,则应省略括号:
- target属性接受字符串值.
- 该字符串是一个固定值,您可以将其烘焙到模板中.
- 这个初始值永远不会改变.
您通常在标准HTML中以这种方式初始化属性,并且它也适用于指令和组件属性初始化.
将元素属性设置为非字符串数据值时,必须使用属性绑定.
总而言之,这意味着只有在使用括号时才会解释右侧的值.每当您在右侧的引号中看到引号时,您可以删除括号:[anyStringProperty]="'hello'"可以更改为anyStringProperty = "hello"
在某些情况下,我们需要动态添加这样的 html 属性,例如来自 api 请求的 json
案例 1 []称为属性绑定
<my-comp [foo]="data.bar"></my-comp>
Run Code Online (Sandbox Code Playgroud)
案例 2 {{ }}称为插值
<my-comp foo="{{data.bar}}"></my-comp>
Run Code Online (Sandbox Code Playgroud)
案例 3条件处理
<my-comp [attr.foo]="data.bar ? true : false"></my-comp>
Run Code Online (Sandbox Code Playgroud)
{{ }} 称为 Interpolation 和 [] 称为 Property Binding 意味着 angular 理解从数据源到查看目标存在单向。
更多信息请访问www.codementor.io
以下是所有情况的简要说明:
当您使用方括号时,右手边是一个表达式。当您根本不使用括号时,右侧是一个常量。
所以将'constant' 字符串分配给my-tag 的输入。用方括号达到同样的效果:注意里面的单引号。如果你没有在那里放单引号,my-tag 的输入将被绑定到它的父组件(你写这个模板的地方)属性或模板变量(例如 ngFor 的 let-constant)命名为“constant”。
在这里形成属性绑定和只是一个常规属性有什么区别
| 归档时间: |
|
| 查看次数: |
3139 次 |
| 最近记录: |