angular - [] 和 {{}} 将状态绑定(bind)到属性的区别?

标签 angular angular2-template

这是一个模板示例:

<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;
  }
}

Plunker example

更多详情请参见 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax

关于angular - [] 和 {{}} 将状态绑定(bind)到属性的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862723/

相关文章:

angular - 仅从 AngularFire 列表中获取新项目

html - 将 HTML(带有 Angular 2 指令)从服务器插入 DOM

angular - <ng-容器> 与 <模板>

javascript - 复制检索到的 json 数据并以文本格式粘贴到文本编辑器中

html - Angular 2 在显示之前渲染单个页面多少次?

angular - 将变量传递给自定义组件

angular - 导入 PDFJS 会破坏 TS 应用程序

javascript - Angular - 模板中调用的模型方法在无限循环中执行

javascript - 如何在 Google ColumnChart 中放置一个图标

Angular 2 Material 动态主题