当我的表单组值之一发生更改时,我尝试禁用表单控件,但问题是方法 disable()
和 enable()
也会更新表单状态,所以我有一个无限循环。
@Component({
selector: 'my-app',
template: `
<form [formGroup]="questionForm">
<input type="text" formControlName="question" />
<input type="text" formControlName="other"/>
</form>
`,
})
export class App {
constructor(private fb: FormBuilder) {
this.questionForm = this.fb.group({
question: [''],
other: ['']
});
}
ngOnInit() {
this.questionForm.valueChanges.subscribe(v => {
if(v.question === 'test') {
this.questionForm.get('other').disable();
} else {
...enable()
}
})
}
}
如何解决这个问题?
最佳答案
嗯,根据official docs您可以使用指令进行自定义验证,这当然可以在您的情况下应用检查用户输入内容的逻辑,然后禁用和启用其他字段。那里有相当多的代码,sooooo...
...如果您不需要所有那堆代码,您也可以进行较小的修改。让我们调用一个函数来检查用户输入的内容。我们还需要绑定(bind)this
,所以我们可以引用questionForm
:
this.questionForm = this.fb.group({
question: ['', [this.checkString.bind(this)]],
other: ['']
});
然后是函数:
checkString(control: FormControl) {
if(control.value == 'test') {
this.questionForm.get('other').disable()
}
// we need to check that questionForm is not undefined (it will be on first check when component is initialized)
else if (this.questionForm) {
this.questionForm.get('other').enable()
}
}
这似乎达到了目的。
Demo
希望这有帮助! :)
关于javascript - Angular 形式禁用对 valueChanges 的控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43479622/