将select标记数据绑定到Angular中的被动表单

将select标记数据绑定到Angular中的被动表单,angular,typescript,reactive-forms,Angular,Typescript,Reactive Forms,我有一个来自后端的JSON格式的数据,前端的select标记是性别,我无法预先选择JSON数据附带的选项。同样从后端,它以enum格式出现,我需要它对男性的1和女性的2进行相应的解析 这是我的后端数据的格式 { "salesPersonId": 13, "name": "testName", "gender": 1, "phone1": "34986215", "phone2": "string", "email": "testingEmail@example.com",

我有一个来自后端的JSON格式的数据,前端的select标记是性别,我无法预先选择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>

性别
1.
2.
它既不会产生任何错误,也不会预先选择来自后端的性别标记。 注意:我使用的是被动形式
提前感谢。

您可以使用角度形式的
setValue
方法,如下所示

<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>
  user = { "name": "testName", "gender": 1 };

  ngOnInit() {
    this.myGroup.controls['gender'].setValue(this.user.gender);
  }
我假设您使用的是
FormGroup
。在HTML中,值应作为属性绑定使用,如下所示

<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>
  user = { "name": "testName", "gender": 1 };

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

请添加表单配置