在角4中,我在json配置文件中定义了以下配置。
countries: ['USA', 'UK', 'Canada'];
default: 'UK'我需要使用反应性模块在下拉列表中显示这些内容。
下面是执行此操作的代码(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中定义的“默认”键。
所以,我试着做这样的事
{{ c}
然而,这是行不通的。默认情况下,如果选中,则为空值。
如何确保在默认情况下选择预定义值?
发布于 2017-10-30 09:23:07
就像这样:
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});
}
}发布于 2017-10-30 09:27:57
以反应形式出现。可以在组件文件和ngValue的使用中进行绑定。欲了解更多细节,请浏览以下链接
https://angular.io/api/forms/SelectControlValueAccessor
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<select formControlName="state">
<option *ngFor="let state of states" [ngValue]="state">
{{ state.abbrev }}
</option>
</select>
</form>
<p>Form value: {{ form.value | json }}</p>
<!-- {state: {name: 'New York', abbrev: 'NY'} } -->
`,
})
export class ReactiveSelectComp {
states = [
{name: 'Arizona', abbrev: 'AZ'},
{name: 'California', abbrev: 'CA'},
{name: 'Colorado', abbrev: 'CO'},
{name: 'New York', abbrev: 'NY'},
{name: 'Pennsylvania', abbrev: 'PA'},
];
form = new FormGroup({
state: new FormControl(this.states[3]),
});
}发布于 2020-02-14 07:15:28
我挣扎着,从IntelliJ IDEA的建议中找到了一种简单有效的方法。
<select id="country" formControlName="country" >
<option [defaultSelected]=true [value]="default" >{{default}}</option>
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 在ts文件中分配值
countries = ['USA', 'UK', 'Canada'];
default = 'UK'只需确保您的formControlName接受字符串,因为您已经将它分配为字符串。
https://stackoverflow.com/questions/47011521
复制相似问题