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

mal*_*awi 5 primeng angular

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

[(selection)]="selectedItem";
Run Code Online (Sandbox Code Playgroud)

看起来像

@Input() selection;
@Output() selection:EventEmitter<any> = new EventEmitter<any>();
Run Code Online (Sandbox Code Playgroud)

我如何实现这样的东西,并且有可能做更多的事情而不是像

 <component-a  [(selection)]="selectedItem"  [(data)]="selectedData"></component-a>
Run Code Online (Sandbox Code Playgroud)

Dmi*_*tko 10

在您的子组件中,您必须像这样实现双向绑定接口:

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>();
Run Code Online (Sandbox Code Playgroud)

@Output通过添加propertyNameChange@Input名称来命名是强制性的。所以你可以像这样在你的父组件模板中使用它:

<mycomponent [(selection)]="fieldInParentComponent"></mycomponent>
Run Code Online (Sandbox Code Playgroud)


Bug*_*ggy 6

角度文档

<app-sizer 
  [(size)]="fontSizePx">
</app-sizer>
Run Code Online (Sandbox Code Playgroud)

双向绑定语法实际上只是属性绑定和事件绑定的语法糖。角型减震器对此具有约束力:

<app-sizer
  [size]="fontSizePx"
  (sizeChange)="fontSizePx=$event">
</app-sizer>
Run Code Online (Sandbox Code Playgroud)

要为属性创建双向绑定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>();
Run Code Online (Sandbox Code Playgroud)

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

changeSelection(newSelection)
{
    this.selection = newSelection;

    // emit change event to parent component
    this.selectionChange.emit(this.selection);  
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

[(x)]语法是很容易证明该元素有名为x一个可设置属性,并命名为相应的事件xChange

这意味着,您只需要selectionChange在子组件上使用相应的方法。因此,如果您希望selectionParentComponentinto的属性进行香蕉盒装绑定,请执行ChildComponent以下步骤:

  1. 在您的ChildComponent:

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

    <child [(selection)]="selection">
    
    Run Code Online (Sandbox Code Playgroud)

总而言之,如果您的属性名称是x,您只需将其对应的 EventEmitter 命名为xChange并为子组件执行香蕉盒式语法,[(x)] = "parentProperty"其余的由 Angular 处理。