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.
app.component.html<div class="mb-3">app.component.ts
<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>
import { Component } from '@angular/core';Demo Select DropDown in Reactive Forms with Angular online:
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
})
}
}
No comments:
Post a Comment