我已经试过效仿这里的其他答案,但我没有成功!我想,这就是我的答案。
我创建了一个反应式表单(即,动态的),我想在任何时候禁用一些字段。我的表单代码。
this.form = this._fb.group({
name: ['', Validators.required],
options: this._fb.array([])
});
const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
value: ['']
}));
我的HTML。
<div class='row' formArrayName="options">
<div *ngFor="let opt of form.controls.options.controls; let i=index">
<div [formGroupName]="i">
<select formArrayName="value">
<option></option>
<option>{{ opt.controls.value }}</option>
</select>
</div>
</div>
</div>
我减少了代码,以方便。我想禁用选择类型的字段。我试着做了以下工作。
form = new FormGroup({
first: new FormControl({value: '', disabled: true}, Validators.required),
});
不起作用!有谁有建议吗?
请注意
如果你在创建一个使用变量作为条件的表单,并试图在以后改变它,它将不会工作,也就是说,表单不会改变。
例如
this.isDisabled = true;
this.cardForm = this.fb.group({
'number': [{value: null, disabled: this.isDisabled},
});
而如果你改变变量
this.isDisabled = false;
时,表单不会改变。你应该使用
this.cardForm.get('number').disable()。
BTW.
你应该使用patchValue方法来改变数值。
this.cardForm.patchValue({
'number': '1703'
});