Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value to Form in Angular 6 using FormControl

<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');

like image 431
chris Avatar asked Aug 23 '18 18:08

chris


People also ask

How do I get the FormControl value in Angular 6?

To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template. city = new FormControl('Noida'); console.


2 Answers

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

like image 179
JCAguilera Avatar answered Nov 14 '22 21:11

JCAguilera


It is not a good idea to mix Reactive Forms and Template Driven Forms together, that is formGroup/formControlName and ngModel binding in the same form control.

If I am not mistaken, this is deprecated in Angular 6, and will be removed in Angular 7. At least that was the warning I got in console few days ago. Simply put, use Reactive Forms if you need to work with dynamic form rendering and complex form validation (cross field validation, custom validators etc.), and use Template Driven Forms for simpler forms that require simple validation.

Now back to your question. In Reactive Forms (in your specific example), a value can be set in the following way:

this.gGroup.controls[this.groupControl].setValue()

Please check the following link: https://stackblitz.com/edit/angular-kskgbp

Hope this helps.

like image 35
Superiom Avatar answered Nov 14 '22 21:11

Superiom