为自定义属性实现双向数据绑定 [英] Implement two-way data binding for custom property
本文介绍了为自定义属性实现双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到在primeng组件中,对类似这样的某些属性使用了ngModel(双向数据绑定)样式
I see in primeng components the use something like ngModel (two-way data binding) style for some property like this
[(selection)]="selectedItem";
看起来像
@Input() selection;
@Output() selection:EventEmitter<any> = new EventEmitter<any>();
我如何实现这样的功能,并且有可能不止像单个属性那样做
how I can implement something like this and is it possible to do for more than single property like
<component-a [(selection)]="selectedItem" [(data)]="selectedData"></component-a>
推荐答案
<app-sizer
[(size)]="fontSizePx">
</app-sizer>
双向绑定语法实际上只是一个语法糖. 属性绑定和事件绑定.角形减震器 绑定到这个:
The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the binding into this:
<app-sizer
[size]="fontSizePx"
(sizeChange)="fontSizePx=$event">
</app-sizer>
要为属性selection
创建双向绑定,请使用:
To create two-way binding for property selection
use:
@Input() selection;
// You have to follow this convention (For Output property)
// i.e. <propertyName><Change> like selectionChange
@Output() selectionChange:EventEmitter<any> = new EventEmitter<any>();
并如下所示更改组件中的选择:
And to change selection in component as shown below:
changeSelection(newSelection)
{
this.selection = newSelection;
// emit change event to parent component
this.selectionChange.emit(this.selection);
}
这篇关于为自定义属性实现双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文