在下拉列表中显示数组中的值,并根据选择过滤键调用 api?

Display value from Array in a dropdown and on the basis of selection filter key and call api?

我正在从 BE api 调用中获取以下数组(我无法更改其非虚拟数据)

let arrayValues = [ { "abc": "1" }, { "ifg": "2" }, { "cdk": "3" }, ];

我想在下拉列表中显示 1,2 和 3 等值。根据下拉列表中的 selected 值,我想获取其密钥并在另一个 api 调用中传递该密钥。

假设如果用户 select 值为 3 那么它应该在另一个 api 调用中传递“cdk”并为另一个下拉列表获取值。 我尝试了下面的代码来打印下拉列表中的值,但我得到了对象 object

     <mat-select *ngFor="let item of arrayValues | keyvalue" [value]="item.key">
                  <mat-option>{{item.value}}</mat-option>
                </mat-select>
              </mat-form-field>

我不确定如何根据值过滤键,请告诉我。

您需要将对象重组为 JSON 格式。

TypeScript 应该是这样的

 arrayValues: any;
 selectedValue: string;
 newArray: any;

  ngOnInit(): void { 
    this.arrayValues = [{ "abc": "1" }, { "ifg": "2" }, { "cdk": "3" }];
    this.newArray = [];
    this.arrayValues.forEach(element => {
    this.newArray.push({ "key": Object.keys(element)[0], "value": Object.values(element)[0] })
});
  }

  onOptionsSelected(): void {
    console.log(this.selectedValue);
  }

HTML应该是这样的

  <mat-form-field>
    <mat-select placeholder="Type" [(ngModel)]="selectedValue" (selectionChange)="onOptionsSelected()">
      <mat-option *ngFor="let type of newArray" [value]="type.key">
        {{ type.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>

该值将在变量 selectedValue 中可用。