角度4-在下拉菜单中选择默认值[反应形式] [英] Angular 4 - Select default value in dropdown [Reactive Forms]
问题描述
在Angular 4中,我在json配置文件中定义了以下配置.
In Angular 4, I have the following configuration defined in a json config file.
countries: ['USA', 'UK', 'Canada'];
default: 'UK'
我需要使用Reactive模块在下拉列表中显示这些内容.
I need to display these in a dropdown using Reactive module.
这是执行此操作的代码(ts)
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>
这完成了工作并在下拉列表中显示了国家. 但是,我还需要默认选择一个国家/地区,并且默认国家/地区来自json中定义的默认"键.
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?
推荐答案
尝试这样:
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});
}
}
这篇关于角度4-在下拉菜单中选择默认值[反应形式]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!