Issue
<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');
Solution
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.
Answered By - Superiom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.