将状态绑定到属性的 [] 和 {{}} 之间的区别? [英] Difference between [] and {{}} for binding state to property?
本文介绍了将状态绑定到属性的 [] 和 {{}} 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个模板示例:
<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>
这里他们都做同样的事情.首选哪一个?为什么?
Here both of them does the same thing. Which one is preferred and why?
推荐答案
[]
用于从父组件中的一个值绑定到一个@Input()
子组件.它允许传递对象.
[]
is for binding from a value in the parent component to an @Input()
in the child component. It allows to pass objects.
{{}}
用于在属性和 HTML 中绑定 strings,如
{{}}
is for binding strings in properties and HTML like
<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>
其中绑定可以是字符串的一部分.
where the binding can be part of a string.
()
用于绑定一个事件处理程序,当 DOM 事件被触发或子组件上的 EventEmitter
发出事件时调用
()
is for binding an event handler to be called when a DOM event is fired or an EventEmitter
on the child component emits an event
@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
这篇关于将状态绑定到属性的 [] 和 {{}} 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文