我想问一下如何设置默认选项?
<form [formGroup]="form2">
<select formControlName="drop">
<option disabled>Choose one</option>
<option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" [selected]="example.isSelected">{{ example.name }}</option>
</select>
</form>
组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-drop-down-list',
templateUrl: './drop-down-list.component.html',
styleUrls: ['./drop-down-list.component.css']
})
export class DropDownListComponent implements OnInit {
public form = new FormGroup({
drop: new FormControl('',
Validators.required,
),
});
public form2 = new FormGroup({
drop: new FormControl('',
Validators.required,
),
});
examples = [{
id: 1, name: 'Test1', isSelected: false, isDisabled: true,
},
{
id: 2, name: 'Test2', isSelected: true, isDisabled: false,
},
{
id: 3, name: 'Test3', isDisabled: false,
}
];
constructor() { }
ngOnInit() {
}
onSubmit(form) {
console.log(form);
}
}
我在堆栈上搜索但我不想将反应形式与ngModel混合,我也不想使用patchValue,因为它只设置默认值而不选择列表中的元素。谢谢你的帮助!
答案 0 :(得分:2)
如果你想选择选项然后这样做,只需在你的formcontrol初始化中传递id值
public form2 = new FormGroup({
drop: new FormControl(this.examples[0].id,
Validators.required,
),
});
或者如果您不想立即初始化并希望稍后再使用setValue方法,那么当您从服务器处理数据时需要以下内容并且想要设置值我只是硬编码值只是为了显示为例,您应该替换为从服务器
获得的值form2.get('drop').setValue('1');
html应如下所示,不需要[selected]
<select formControlName="drop">
<option disabled>Choose one</option>
<option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" >{{ example.name }}</option>
</select>