4

I've a JSON formatted data coming from back-end, with gender as a select tag in front-end I'm unable to pre-select the option that comes with json data. Also from back-end it comes in enum format and I need it to parse accordingly 1 for Male and 2 for Female here is the format of my back-end data,

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

and here's what I'm trying to get it bind with my received data,

 <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>

neither it produces any error nor do it pre-select the gender tag that comes from back-end. Note: I'm using reactive forms Thanks in advance.

1
  • Please add your form configuration Commented Nov 18, 2019 at 8:18

1 Answer 1

3

You can use setValue method in Angular Forms as follows.

I will assume that you are using FormGroup. In HTML value should be used as a property binding as follows.

<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>

Change your TS as follows.

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

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

StackBlitz Demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.