在Angular中将选择标签数据绑定到响应式表单

4

我从后端得到了一个JSON格式的数据,在前端使用下拉选择标签时,无法预先选择与json数据匹配的选项。此外,从后端获取的数据是enum格式,我需要相应地解析1男性2女性。这是我后端数据的格式:

{
  "salesPersonId": 13,
  "name": "testName",
  "gender": 1,
  "phone1": "34986215",
  "phone2": "string",
  "email": "testingEmail@example.com",
  "team": "Bravo",
  "teamLeader": "Delta",
  "countyId": 1,
  "county": null,
  "subCountyId": 1,
  "subCounty": null,
  "address": "House 108",
  "additionalInfo": "He Drinks tea",
  "input1": "string",
  "input2": "string"
}

这里是我尝试将其与接收到的数据绑定的内容:

 <mat-form-field appearance="outline" fxFlex="33" class="pr-4">
    <mat-label>Gender</mat-label>
    <mat-select formControlName="gender">
        <mat-option value="1">1</mat-option>
        <mat-option value="2">2</mat-option>

    </mat-select>
</mat-form-field>

无论是没有产生任何错误,也没有预先选择来自后端的性别标签。注意:我正在使用响应式表单。谢谢。


请添加您的表单配置。 - Cristiano Casciotti
1个回答

3

您可以按以下方式在Angular表单中使用setValue方法。

假设您正在使用FormGroup。 在HTML中,应将value用作属性绑定,如下所示。

<form [formGroup]="myGroup">
  <mat-form-field>
  <mat-label>Gender</mat-label>
  <mat-select formControlName="gender">
    <mat-option [value]="1">Male</mat-option>
    <mat-option [value]="2">Female</mat-option>
  </mat-select>
</mat-form-field>
</form>

请按照以下方式更改您的TS。

  user = { "name": "testName", "gender": 1 };

  ngOnInit() {
    this.myGroup.controls['gender'].setValue(this.user.gender);
  }

StackBlitz演示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接