【发布时间】:2019-11-13 02:05:35
【问题描述】:
注意 - 我在末尾添加了一个 stackblitz 链接。
我的代码存在问题,如果当前填充了另一个表单控件,我希望基本上禁用一个表单控件。例如,如果字段 A 已填充,则输入字段 B 和 C 将被禁用。如果字段 A 被清除,则字段 B 和 C 将重新启用。这发生在所有三个字段中,按其各自的顺序表示,如果您填充 B,则 A 和 C 将被禁用,等等。
this.SearchForm.get('a').valueChanges
.subscribe( ( value ) => {
if ( value ) {
this.SearchForm.get('b').disable();
this.SearchForm.get('c').disable();
} else {
this.SearchForm.get('b').enable();
this.SearchForm.get('c').enable();
}
});
如果我只在一个字段上设置它,那么效果很好。但是,如果我将其更改为包括设置其他字段,如下所示:
this.SearchForm.get('a').valueChanges
.subscribe( ( value ) => {
if ( value ) {
this.SearchForm.get('b').disable();
this.SearchForm.get('c').disable();
} else {
this.SearchForm.get('b').enable();
this.SearchForm.get('c').enable();
}
});
this.SearchForm.get('b').valueChanges
.subscribe( ( value ) => {
if ( value ) {
this.SearchForm.get('a').disable();
this.SearchForm.get('c').disable();
} else {
this.SearchForm.get('a').enable();
this.SearchForm.get('c').enable();
}
});
this.SearchForm.get('c').valueChanges
.subscribe( ( value ) => {
if ( value ) {
this.SearchForm.get('a').disable();
this.SearchForm.get('b').disable();
} else {
this.SearchForm.get('a').enable();
this.SearchForm.get('b').enable();
}
});
我收到“超出最大调用堆栈大小”错误。也许有更好的方法可以使用反应形式来做到这一点,但我还没有遇到任何事情。我采用这种方法的部分原因是,一旦该字段为空,它将用更少的代码轻松地重新启用其他字段。
Link of Stackblitz 如果你注释掉 b 和 c 的 valueChanges 并且只有一个,你可以看到我正在寻找的那种行为,但是如果你添加一个额外的 valuechanges 就会得到错误。
【问题讨论】:
-
可能是因为启用/禁用其他 formControl 会触发其更改监听器
标签: angular angular-reactive-forms