为自定义属性实现双向数据绑定

时间:2018-09-12 08:03:17

标签: angular primeng

我看到在primeng组件中对某些属性使用了类似ngModel(双向数据绑定)样式

[(selection)]="selectedItem";

外观

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

我如何实现这样的功能,并且有可能不仅仅对单个属性进行操作

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

4 个答案:

答案 0 :(得分:4)

https://angular.io/guide/template-syntax#two-way-binding

  

当元素具有名为x的可设置属性和名为[(x)]的相应事件时,xChange语法很容易演示。

这意味着,您只需要在子组件上使用相应的selectionChange方法。因此,如果您希望将selection的属性ParentComponent的香蕉装箱绑定到ChildComponent,请按照以下步骤操作:

  1. 在您的ChildComponent中添加以下内容:

    @Input() selection;
    @Output() selectionChange = new EventEmitter<any>();
    
  2. 在您的ParentComponent模板中:

    <child [(selection)]="selection">
    

总而言之,如果您的属性名称为x,则只需将其对应的EventEmitter命名为xChange,并为子组件{{1}做“ banner-in-a-box”语法},Angular负责其余的工作。

答案 1 :(得分:3)

Angular docs

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

双向绑定语法实际上只是一个语法糖   属性绑定和事件绑定。角形减震器   绑定到这个:

<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);  
}

答案 2 :(得分:2)

在子组件中,您必须实现双向绑定接口,如下所示:

private _selection: any;
get selection(): any {
    return this._selection;
}
@Input()
set selection(value: any) {
    if(this._selection === value) {
        return;
    }
    this._selection = value;
    this.selectionChange.emit(this._selection);
}
@Output()
selectionChange = new EventEmitter<any>();

必须通过在@Output名称上添加propertyNameChange来命名@Input。 因此,您可以像这样在父组件中使用它:

<mycomponent [(selection)]="fieldInParentComponent"></mycomponent>

答案 3 :(得分:0)

在子组件(组件a)中,您需要一个@output

@Output() change:EventEmitter = new EventEmitter();

然后通过

通知父组件有关更改的值
change.emit(newValue);

另请参阅Angular2:https://stackoverflow.com/a/33220997/3710630