【问题标题】:Parse value from object in Angular template从Angular模板中的对象解析值
【发布时间】:2022-01-26 21:18:16
【问题描述】:

#对象

[
    {
        "id": 1,
        "description": "1 - Gulf Coast"
    },
    {
        "id": 2,
        "description": "10 - West Great Lakes"
    },
    {
        "id": 3,
        "description": "11 - California"
    },
]

#html代码

<mat-form-field appearance="fill" >
    <mat-label>Region</mat-label>
    <mat-select [(ngModel)]="territoryAssignmentFields.region" name="region">
        <mat-option *ngFor="let region of regions" [value]="region.id">{{ region.description }}</mat-option>
    </mat-select>
</mat-form-field>

我们如何在角度模板上解析 mat-select 选项的值将是描述对象中的 id,例如基于 [value] 下面的对象应该是:

1、10、11。

它应该从描述中获取id或数字,然后将其用作mat-select选项的[value]

我们可以在模板上解析它吗?谢谢。

#tscode

getregion() {
  this.searchString = "";
  this._pickListService.getregion(this.accountId,this.searchString).subscribe(
    res => {
      this.regions = res.data;
      console.log(" this.regions",  this.regions) 
    },
    err => {
      console.log('Filtered Territory Assignments Region Error')
      console.log(err);
    }
  )
}

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

在订阅事件中,用Array.map()生成一个新数组,id为:

  1. description 值拆分为- 符号。
  2. 从 (1) 中获取第一个值。
  3. 从 (2) 修剪间距。
  4. 从 (3) 转换为 number 类型。
this._pickListService
  .getregion(this.accountId, this.searchString)
  .subscribe(
    (res) => {
      let data: any[] = res.data.map((x: any) => {
        return {
          id: parseInt(x.description.split('-')[0].trim()),
          description: x.description
        };
      });

      this.regions = data;
      console.log(' this.regions', this.regions);
    },
    (err) => {
      console.log('Filtered Territory Assignments Region Error');
      console.log(err);
    }
  );

Sample Demo on StackBlitz

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 2017-10-24
    • 2018-09-30
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 2015-12-10
    相关资源
    最近更新 更多