angular 组件间的双向绑定

组件间的 双向绑定

child.component.ts

...
@Component({
  selector: 'app-child',
  template: `
    childname-text:{{childName}}<br/>
    <button (click)=reset()>reset</button>`
})

export class ChildComponent{
  @Input() childName:string = '';
  @Output() childNameChange = new EventEmitter<string>();

  reset(person:string):void{
    this.childName = '王二麻子';
    this.childNameChange.emit(this.childName); 
  }
}

/*
注意:EventEmitter的命名格式:xxxChange
xxx为双向绑定的哪个变量名,本例子中是childName,所以EventEmitter为childNameChange
*/

parent.component.ts

...
@Component({
  selector: 'app-parent',
  template: `
    <div>parent-text: {{parentName}}</div>
    <app-child [(childName)]='parentName'></app-child>`
})

export class ParentComponent{
  parentName:string = '貂蝉';
}

双向绑定语法实际上是属性绑定和事件绑定的语法糖。 Angular 将 parent.component.ts 里面<app-child>的绑定分解成这样:

// <app-child [(childName)]='parentName'></app-child> 等价于下面的代码

<app-child [childName]='parentName' (childNameChange)='parentName=$event'></app-child>

运行结果:

发布了112 篇原创文章 · 获赞 149 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/l284969634/article/details/102552349