角@Input,将对象绑定到同一对象但具有不同的属性名称

时间:2019-01-17 06:30:54

标签: angular

我阅读了文档,您可以像下面那样更改属性名称:@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>

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以使自己更舒适(但等同于无私)

_radioButtons:any={"Name"."",Color:"",Rank:""} //<--define a model
@Input('buttons')
set radioButtons(value: any) {
    for (let property in this.model)
    {
      //You can use x.indexOf(property)>=0 or x.endWidth(property)
      let field=Object.keys(value).find(x=>x.indexOf(property)>=0);
      this._radioButtons[property]=field?value[field]:null
    }
}