0

HTML -

<select id="gender" formControlName="gender" [(ngModel)]="gender">
            <option value="" disabled selected hidden>Gender</option> 
            <option [value]="gender" *ngFor="let gender of genderObj">{{gender}}</option> 
</select>

TS -

genderObj = ['Male', 'Female', 'Other'];

ngOnInit(): void {
    this.formDetails();
}

initForm() {
    this.Form = this.formBuilder.group({
      gender: ['', Validators.compose([Validators.required])]
    });
  }

 formDetails() {
    this.userService.getFormDetails(this.Id)
      .subscribe((res: any) => {
        this.data = res.body.data;
      });
  }

I want to get a prefilled/autoselected value of dropdown if the value of gender from API is gender:'M' then Male. If value is gender:"F" then Female. And if empty string then Select gender placeholder. Tried with setValue and patchValue but nothing comes.

Bozhinovski
  • 2,496
  • 3
  • 20
  • 38
  • why use `ngModel` and reactive forms? see here for why https://stackoverflow.com/questions/40458739/two-way-binding-in-reactive-forms#:~:text=You%20can%20use%20%5B(ngModel)%5D%20with%20Reactive%20forms.&text=This%20will%20a%20completely%20different,NgModel%20directive%20would%20be%20used. – Ric Oct 19 '20 at 13:35

1 Answers1

0

Inside the .subscribe block you can set the gender of the form. As we do not know the structure of your returned data, you have to implement the gender specific stuff on your own. Setting the forms value, you can do the following:

this.form.gender.patchValue(...) <-- set the value here

Marek W
  • 699
  • 4
  • 14