Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
482 views
Welcome To Ask or Share your Answers For Others

1 Answer

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});
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...