angular - 为自定义属性实现双向数据绑定
问题描述
我在primeng组件中看到对这样的一些属性使用类似ngModel(双向数据绑定)样式的东西
[(selection)]="selectedItem";
它看起来像
@Input() selection;
@Output() selection:EventEmitter<any> = new EventEmitter<any>();
我如何实现这样的事情,是否可以为多个单一属性做
<component-a [(selection)]="selectedItem" [(data)]="selectedData"></component-a>
解决方案
<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);
}
推荐阅读
- python - 试图在不和谐 python bot 中使用多个 f 字符串不起作用
- java - mockito 测试通知用户某些事件的 void 方法不起作用
- html - 如何用虚线水平分隔两个文本即:text1............text2
- android - BottomNavigationView - Android Studio
- python - 在文件中替换和写入多个数据
- typescript - 如果输入对象具有属性“x”,则将字段“x”添加到类
- c# - C# 控制台应用程序 - 连接到 Oracle 12c
- ibm-cloud - 您好,我目前正在学习 IBM 课程,但我的启用持续交付按钮不起作用。我该怎么办?
- string - 处理字符串格式不加零
- php - PHP 中的 Google FCM 显示 IOS 推送通知错误,但在 Android 上工作