这是一个模板示例:
<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>
这里他们两个做同样的事情。首选哪一个?为什么?
最佳答案
[]
用于从父组件中的值绑定(bind)到子组件中的 @Input()
。它允许传递对象。
{{}}
用于在属性和 HTML 中绑定(bind) strings
<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>
绑定(bind)可以是字符串的一部分。
()
用于绑定(bind)事件处理程序,以便在触发 DOM 事件或子组件上的 EventEmitter
发出事件时调用
@Component({
selector: 'child-comp',
template: `
<h1>{{title}}</h1>
<button (click)="notifyParent()">notify</button>
`,
})
export class ChildComponent {
@Output() notify = new EventEmitter();
@Input() title;
notifyParent() {
this.notify.emit('Some notification');
}
}
@Component({
selector: 'my-app',
directives: [ChildComponent]
template: `
<h1>Hello</h1>
<child-comp [title]="childTitle" (notify)="onNotification($event)"></child-comp>
<div>note from child: {{notification}}</div>
`,
})
export class AppComponent {
childTitle = "I'm the child";
onNotification(event) {
this.notification = event;
}
}
更多详情请参见 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax
关于angular - [] 和 {{}} 将状态绑定(bind)到属性的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862723/