【发布时间】:2021-03-09 16:32:24
【问题描述】:
我有一个输入和一个复选框,如果选中复选框,我想禁用输入。有什么建议吗?
<input formControlName="checkbox" type="checkbox">
<input formControlName="input" type="number">
【问题讨论】:
标签: angular angular-reactive-forms angular-forms
我有一个输入和一个复选框,如果选中复选框,我想禁用输入。有什么建议吗?
<input formControlName="checkbox" type="checkbox">
<input formControlName="input" type="number">
【问题讨论】:
标签: angular angular-reactive-forms angular-forms
您可以在复选框控件上使用可观察的反应形式 valueChanges 来实现此目的。
@Component({...})
export class MyComponent implements OnInit {
// Your form
form:FormGroup = this.fb.group({checkbox: false, input: ''});
constructor(private fb:FormBuilder){}
ngOnInit() {
// Subscribe to value changes - this will trigger whenever the value of your checkbox is changed (through click, or programmatically)
this.form.get('checkbox').valueChanges
.subscribe(value => {
if (value) {
// disable the input when new value is true
this.form.get('input').disable();
} else {
// (re-)enable the input when new value is false
this.form.get('input').enable();
}
})
}
}
【讨论】: