以编程方式禁用反应式表单组件
Programmatically disable a reactive form component
我了解如何指定要禁用的反应式表单控件的初始状态。
someControl: [{value: '', disabled: true}]
我以后如何根据在表单中选择的另一个值以编程方式更改禁用状态。所以,例如如果 anotherControl
在下拉列表中选择了某个值,则应禁用 someControl
,否则应启用。
谢谢
这应该有效
this.someControl.reset({value: '', disabled: true});
您可以使用 select 字段查看 valueChanges
,这是一个带有下拉列表和输入字段的示例,我们将根据从下拉列表中选择的值 disable/enable :
this.myForm = this.fb.group({
selects: [''],
inputField: ['']
})
// subscribe to changes in select field, if the value chosen is "two",
// disable input field, else enable field
this.myForm.get('selects').valueChanges.subscribe(val => {
if(val === 'two') {
this.myForm.get('inputField').disable()
}
else {
this.myForm.get('inputField').enable()
}
})
这是一个
DEMO
编辑:
根据 developer033 的建议,您还可以使用简单的更改事件,其中模板...
<select formControlName="selects" (change)="checkValue()">
<option disabled></option>
<option *ngFor="let a of arr">{{a}}</option>
</select>
组件将是:
checkValue() {
if(this.myForm.get('selects').value === 'two') {
this.myForm.get('inputField').disable()
}
else {
this.myForm.get('inputField').enable()
}
}
我了解如何指定要禁用的反应式表单控件的初始状态。
someControl: [{value: '', disabled: true}]
我以后如何根据在表单中选择的另一个值以编程方式更改禁用状态。所以,例如如果 anotherControl
在下拉列表中选择了某个值,则应禁用 someControl
,否则应启用。
谢谢
这应该有效
this.someControl.reset({value: '', disabled: true});
您可以使用 select 字段查看 valueChanges
,这是一个带有下拉列表和输入字段的示例,我们将根据从下拉列表中选择的值 disable/enable :
this.myForm = this.fb.group({
selects: [''],
inputField: ['']
})
// subscribe to changes in select field, if the value chosen is "two",
// disable input field, else enable field
this.myForm.get('selects').valueChanges.subscribe(val => {
if(val === 'two') {
this.myForm.get('inputField').disable()
}
else {
this.myForm.get('inputField').enable()
}
})
这是一个
DEMO
编辑:
根据 developer033 的建议,您还可以使用简单的更改事件,其中模板...
<select formControlName="selects" (change)="checkValue()">
<option disabled></option>
<option *ngFor="let a of arr">{{a}}</option>
</select>
组件将是:
checkValue() {
if(this.myForm.get('selects').value === 'two') {
this.myForm.get('inputField').disable()
}
else {
this.myForm.get('inputField').enable()
}
}