Monday, November 11, 2019

Select DropDown in Reactive Forms with Angular 7|8|9

When we work on select dropdown in Angular application, we must set dynamic values in the form control array. Since the user can select any values from the dropdown list we should use setValue() method to assign the dynamic values to form control array.
Select DropDown in Reactive Forms with Angular 7|8|9

app.component.html
<div class="mb-3">
   <label>State</label>
   <select class="custom-select d-block w-100" (change)="changeCity($event)" formControlName="cityName">
      <option value="">Choose...</option>
      <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
   </select>
</div>
app.component.ts
import { Component } from '@angular/core';
import { FormBuilder } from "@angular/forms";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   // City names
   City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan']
   registrationForm = this.fb.group({
    address: this.fb.group({
      city: ['']
    })
   })
  changeCity(e) {
   this.registrationForm.get('address.cityName').setValue(e.target.value, {
    onlySelf: true
   })
  }
}
 Demo Select DropDown in Reactive Forms with Angular online:

No comments:

Post a Comment