Maihan Nijat
Maihan Nijat

Reputation: 9354

How to set select value using Reactive form and looping through array

I am trying to set select value dynamically but the changes are not reflected even with using detect changes.

Component:

export class AppComponent implements OnInit {

  constructor(private cd: ChangeDetectorRef) {

  }
  genders=['male','female'];
  SignupForm:FormGroup;

  ngOnInit(){
    this.SignupForm = new FormGroup({
      'gender':new FormControl(),
    });
  }

  onSubmit(){
    console.log(this.SignupForm);
  }

  setGender() {
    this.SignupForm.controls.gender.setValue(this.genders[1]);
    console.log(this.SignupForm.controls.gender.value);
    this.cd.detectChanges();
  }
}

Template:

<div class="container">
    <div class="row">
        <div class="col-xs-12 col-sm-10 col-md-8 col-md-offset-2 col-sm-offset-1">
            <form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
                <select fromControlName="gender">
         <option *ngFor="let g of genders">{{g}}</option>
       </select>

        <button class="btn btn-primary" type="submit">Submit</button> 
      </form>
    </div>
  </div>
</div>

<button class="btn btn-primary" (click)="setGender()">Set Female</button>

Stackblitz

Upvotes: 1

Views: 78

Answers (2)

dev-dan
dev-dan

Reputation: 6293

I think you can try something looking like the following, this would be selecting a default option for the select / option by getting it to read the value of the form control which would be set early into the lifecycle of the component.

Solution

Add this to your options to set the default the the form value.

<option *ngFor="let g of genders" [selected]="gender.value">{{g}}</option>

Then within your component.

public ngOnInit(): void {
this.SignupForm = new FormGroup({
  'gender':new FormControl(),
 });
}

public setGender(): void
{
     this.gender.setValue(this.genders[1]);
     this.cd.detectChanges();
     console.log(this.gender) // just check here the value is set correct.  
}

public get gender(): AbstractControl
{
    return this.SignupForm.controls['gender']
}

This should give the the required functionality. Looking a little neater. Here is an article someone wrote on the subject. All the best.

Upvotes: 1

Kalamarico
Kalamarico

Reputation: 5666

You have a very little error, see:

<select fromControlName="gender">

Change by:

<select formControlName="gender">

Upvotes: 1

Related Questions