<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');
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With