首页 > 解决方案 > 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>

因此传入的对象将始终具有相同的结构,但名称应该更改,以便我可以在组件外部拥有自定义属性名称,但在组件内部拥有通用属性名称......

标签: angular

解决方案


您必须将传递的模型映射到您的内部模型。

首先,您必须使用属性而不是类变量(至少是 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...
    }
}

推荐阅读