首页 > 解决方案 > 为自定义属性实现双向数据绑定

问题描述

我在primeng组件中看到对这样的一些属性使用类似ngModel(双向数据绑定)样式的东西

[(selection)]="selectedItem";

它看起来像

@Input() selection;
@Output() selection:EventEmitter<any> = new EventEmitter<any>();

我如何实现这样的事情,是否可以为多个单一属性做

 <component-a  [(selection)]="selectedItem"  [(data)]="selectedData"></component-a>

标签: angularprimeng

解决方案


角度文档

<app-sizer 
  [(size)]="fontSizePx">
</app-sizer>

双向绑定语法实际上只是属性绑定和事件绑定的语法糖。Angular 将绑定脱糖成这样:

<app-sizer
  [size]="fontSizePx"
  (sizeChange)="fontSizePx=$event">
</app-sizer>

selection要为属性使用创建双向绑定:

@Input() selection;

// You have to follow this convention (For Output property)
// i.e. <propertyName><Change> like selectionChange

@Output() selectionChange:EventEmitter<any> = new EventEmitter<any>();

并更改组件中的选择,如下所示:

changeSelection(newSelection)
{
    this.selection = newSelection;

    // emit change event to parent component
    this.selectionChange.emit(this.selection);  
}

推荐阅读