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

Nar*_*sty 13 angular2-template angular

这是一个模板示例:

<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>
Run Code Online (Sandbox Code Playgroud)

在这里他们两个都做同样的事情.哪个是首选,为什么?

Gün*_*uer 22

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

{{}}用于绑定属性和HTML中的字符串

<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>
Run Code Online (Sandbox Code Playgroud)

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

()用于绑定在触发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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker的例子

有关详细信息,请访问https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax


Wil*_*een 7

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

理解它的主要内容如下:

插值是一种特殊的语法,Angular 将其转换为属性绑定。它是属性绑定的便捷替代方案。

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

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

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

  1. 字符串连接与字符串插值:

      <img src=' https://angular.io/{{imagePath}}'/>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 字符串插值不能用于字符串以外的任何东西

      <myComponent  [myInput]="myObject"></myComponent>
    
    Run Code Online (Sandbox Code Playgroud)

myInput是一个@Input()ofmyComponent并且我们想要传入一个对象时,我们必须使用属性绑定。如果我们使用字符串插值,对象将被转换为一个字符串,并且这将作为 的值传入myInput