angular - Angular @Input,将对象绑定到同一对象但具有不同的属性名称
问题描述
我在文档中读到您可以更改属性名称,如下所示:@Input('account-id') id: string;
但是有没有办法将对象中的属性名称更改为不同的名称?
我有一个可重用的单选按钮组件,它接受一个我希望如下所示的对象:
export class ICustomRadioButton {
name: string;
color: string;
rank: number;
}
// ...
@Input('buttons') radioButtons: ICustomRadioButton;
但我希望传递给单选按钮组件的对象如下所示:
Sample1: {levelName: 'One', levelColor: #ffffff, levelRank: 2}
Sample2: {cutomerName: 'Alfa', cutomerColor: #ffffff, cutomerRank: 4}
<app-custom-radio-group [buttons]='customerInfo' (buttonPicked)='buttonPicked($event)'></app-custom-radio-group>
因此传入的对象将始终具有相同的结构,但名称应该更改,以便我可以在组件外部拥有自定义属性名称,但在组件内部拥有通用属性名称......
解决方案
您必须将传递的模型映射到您的内部模型。
首先,您必须使用属性而不是类变量(至少是 setter):
// since this is plural, you probably want an array instead?
private _buttonsModel: ICustomRadioButton = {};
// we'll use "any" type, since we don't know the property names
private _radioButtons: any;
get radioButtons(): any {
return this._radioButtons;
}
@Input('buttons')
set radioButtons(value: any) {
this._radioButtons = value;
// mapping: you got different solutions here, for example Object.keys etc.
// for-in loops through all properties
for (const property in value) {
// now compare the property names to the ones you're looking for
if (property.endsWith('Name') { this._buttonsModel.name = value[property]; }
// etc...
}
}
推荐阅读
- button - Android RecyclerView 列表项 - 按钮不采用意图命令
- python - 如何在 Python 中按工作日过滤负回报和正回报?
- python - 使用 Python Selenium 导航到下一页时遇到问题
- java - 有没有办法确定正在运行的项目是 .war 还是 .jar 文件?
- python - 无法从 Google Compute Engine 实例运行 Hello World Python 应用程序
- hibernate - Hibernate 5不在Oracle DB中提交/保存记录
- css - 可以用纯 CSS 禁用 SVG SMIL 动画吗?
- c# - Xamarin 表单两种方式绑定日期属性时间重置
- python - pip install --no-build-isolation 不返回这样的选项:--no-build-isolation
- php - 当列名和参数名不同时如何检查唯一名称