How to set value to Form in Angular 6 using FormControl

chris picture chris · Aug 23, 2018 · Viewed 40.3k times · Source
<div class="form-group" [formGroup]="gGroup">
  <label for="grouplabel">Group</label>
  <select formControlName="groupControl" [(ngModel)]="groupobj" (ngModelChange)="onSelectGroup($event)" id="group" class="form-control">
        <option>Select</option>
        <option *ngFor="let group of groups" [selected]="current_group === group.name">{{group.name}}</option>
  </select>
</div>

How can I set the value of the <select> field to Select dynamically in the Component?

I looked at the docs, https://angular.io/api/forms/FormControlName#use-with-ngmodel but still no example that can help me.

Attempt:

this.gGroup.get('groupControl').setValue('Select');

Answer

JCAguilera picture JCAguilera · Aug 23, 2018

I figured out a way to do this:

<form #f="ngForm">
  <select name="option" ngModel>
    <option value="" disabled>Choose an option</option>
    <option *ngFor="let option of options" [ngValue]="option">
      {{ option.title }}
    </option>
  </select>
</form>

this.f.controls.state.setValue(this.options[0]);

Check this example I made:

https://stackblitz.com/edit/angular-xpeth8