且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[]和{{}}之间的区别在于将状态绑定到属性吗?

更新时间:2023-11-12 22:30:40

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

[] is for binding from a value in the parent component to an @Input() in the child component. It allows to pass objects.

{{}}用于在属性和HTML之类的

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