In Angular 4, I have the following configuration defined in a json config file.
countries: ['USA', 'UK', 'Canada'];
default: 'UK'
I need to display these in a dropdown using Reactive module.
Here is the code to do this (ts)
countries: string[] = [];
default: string;
...
this.countries = config.countries;
this.default = config.default;
html
<select id="country" formControlName="country" >
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
This does the job and displays the countries in a drop down. However, I also need to select a country by default and the default country comes from the 'default' key defined in json.
So, I tried doing something like this
{{ c }}
However, this does not work. By default an empty value if selected.
How can I make sure that a predefined value is selected by default?
Try like this :
component.html
<form [formGroup]="countryForm">
<select id="country" formControlName="country">
<option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
</select>
</form>
component.ts
import { FormControl, FormGroup, Validators } from '@angular/forms';
export class Component {
countries: string[] = ['USA', 'UK', 'Canada'];
default: string = 'UK';
countryForm: FormGroup;
constructor() {
this.countryForm = new FormGroup({
country: new FormControl(null);
});
this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
}
}