angular:无法使用@input getter和setter设置对象

问题描述 投票:1回答:1

我基本上试图将对象转换为数组并将其绑定到kendo-dropdown控件。当我指向@Input绑定时,下拉列表会绑定,但会提示错误,指出不支持data.map。基本上,下拉列表需要一个数组对象。当我为@Input使用getter和setter属性时,我将基金类视为未定义。有人可以告诉我问题是什么

get fundclass(): any {
    return this._fundclass;
}

@Input()
set fundclass(fundclass: any) {
    if (this.fundclass !== undefined ) {
        this._fundclass =  Object.keys(this.fundclass).map(key => ({type: key, value: this.fundclass[key]}));
    }
}

JSON - 为了清楚起见,我在调试期间完成了对象的JSON.parse,以显示对象的内部结构是什么样的

"[{"FundClassId":13714,"FundClass":"Class D"},{"FundClassId":13717,"FundClass":"Class B"},{"FundClassId":13713,"FundClass":"Class A"},{"FundClassId":13716,"FundClass":"Class B1"},{"FundClassId":13715,"FundClass":"Class C"}]"

HTML

<kendo-dropdownlist style="width:170px" [data]="fundclass" [filterable]="false"
            [(ngModel)]="fundclass" textField="FundClass" [valuePrimitive]="true"
            valueField="FundClassId"  (valueChange)="flashClassChanged($event)"></kendo-dropdownlist>

根据以前的建议更新了代码和UI。这里的问题是我看不到所有我看到的显示值是底层值,即id的值

_fundclass: any;

      get fundclass(): any {
        return this._fundclass;
      }

      @Input()
      set fundclass(fundclass: any) {
        if (fundclass !== undefined ) {
         this._fundclass =  Object.keys(fundclass).map(key => ({text: key, value: fundclass[key]}));
        }
      }

标记

<kendo-dropdownlist style="width:170px" [data]="fundclass" [filterable]="false"
            [(ngModel)]="fundclass" textField="key" [valuePrimitive]="true"
            valueField="fundclass[key]"  (valueChange)="flashClassChanged($event)"></kendo-dropdownlist>
angular
1个回答
0
投票

您正在使用引用对象属性的this.fundclass,因此删除该this部分以获取函数参数。

@Input()
set fundclass(fundclass: any) {
  if (fundclass !== undefined ) {
  //--^^^^^^^^--- here
     this._fundclass =  Object.keys(fundclass).map(key => ({text: key, value: fundclass[key]}));
     // ---------------------------^^^^^^^^^^^---------------------------------^^^^^^^^^^^^^^^----- here
  }
}

您甚至可以使用Object.entries()方法与Destructuring assignment来简化您的代码。

@Input()
set fundclass(fundclass: any) {
  if (fundclass !== undefined ) {
     this._fundclass =  Object.entries(fundclass).map(([text, value]) => ({text, value}));
  }
}

更新:问题在于您使用相同模型的模型绑定,而绑定将其更改为其他模式,否则当您更改值时,所选值将设置为_fundclass属性值,但下拉数据应为数组。

模板:

<kendo-dropdownlist style="width:170px" [data]="fundclass" [filterable]="false"
        [(ngModel)]="fundclass1" textField="FundClass" [valuePrimitive]="true"
        valueField="FundClassId"  (valueChange)="flashClassChanged($event)"></kendo-dropdownlist>

TS:

_fundclass:any;
fundclass1:any;

get fundclass(): any {
    return this._fundclass;
}

@Input()
set fundclass(fundclass: any) {
    if (this.fundclass !== undefined ) {
        this._fundclass =  Object.keys(this.fundclass).map(key => ({type: key, value: this.fundclass[key]}));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.