简体   繁体   中英

how to set default select value with angular2 reactive forms?

I have this reactive form:

<form [formGroup]="myForm" novalidate>
  <div *ngIf="myForm.get('id').value === 'Person'">
   <div formGroupName="person">
      <select class="form-control" formControlName="name"> 
        <option selected="selected">XX</option>  //Cannot make this work      
        <option *ngFor="let n of names" [value]="n">{{n}}</option>
      </select>
    <label>Select a name</label>
   </div>
  </div>
    // etc
</form>

I cannot set a default selected value to my select tag, why it doesnt work?

You can set value as empty:

<option value="">XX</option>

and when building your form, just set default value to empty:

name: ['']

Demo

The way to select a value by default is in the component:

formControl: FormControl = new FormControl('yourValue');

You can also patch a value:

formControl.patchValue('anotherValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM