Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

Angular 4 - Select default value in dropdown [Reactive Forms]

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...