[] 和 {{}} 绑定状态到 属性 的区别?

Difference between [] and {{}} for binding state to property?

这是一个模板示例:

<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>

这里他们两个做同样的事情。首选哪一个?为什么?

[] 用于从父组件中的值绑定到子组件中的 @Input()。它允许传递对象。

{{}} 用于在属性中绑定 字符串 并且 HTML 类似于

<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>

绑定可以是字符串的一部分。

() 用于绑定事件处理程序,当触发 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

字符串插值与属性绑定的区别:

主要了解以下几点:

Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding.

这意味着 在幕后它会产生类似的结果。然而,字符串插值有一个重要的限制。这是将首先评估字符串插值内的所有内容(尝试从模型 ts 文件中查找值):

  • 如果在那里找不到该值,则字符串插值中的值将被评估为字符串。
  • 如果在模型中找到该值,则找到的值将被强制转换为字符串并使用。

这对您如何使用这 2 种方法有一些影响。例如:

  1. 带字符串插值的字符串连接:

      <img src=' https://angular.io/{{imagePath}}'/>
    
  2. 字符串插值只能用于字符串

      <myComponent  [myInput]="myObject"></myComponent>
    

myInputmyComponent@Input(),我们要传入一个对象,就必须使用属性绑定。如果我们要使用字符串插值,对象将变成一个字符串,并将作为 myInput.

的值传入

战斗结束后我来得有点晚:),但是,据我所知,还有另一个区别有时可能非常重要。 顾名思义,“属性 绑定”意味着您绑定到 HTML 元素“对象”的 属性(对应于它的DOM)中的“objective”表示,与字符串插值不同,可以应用于HTML元素标签属性 ,这就是为什么你只能在其中放入字符串的原因,因为你正在与一个非 parsed/parseable 实体交谈。

很多时候,两者之间有直接对应关系(html 中的标记有一个 foo 属性,它链接到 DOM 对象的 foo 属性) ,但这不是规则,您可以拥有未链接到属性的属性以及相反的属性。

顺便说一句,你在堆栈溢出中有一个很好的答案,它深刻地解释了两者之间的区别:What is the difference between properties and attributes in HTML?