Angular 5 - 如何在表单值更改时添加条件字段 [英] Angular 5 - How to add Conditional Fields on Form Value Change
问题描述
我致力于应用条件字段逻辑.其中两个字段取决于它们的值.
I working on applying conditional field logic. Where two fields are dependant on their value.
要求:假设我们有一个具有以下值的单选按钮:
Requirement: Let's say, we've a radio button with following values:
是否要格式化此代码: o 是 o 否
如果用户选择否,则什么也不会发生.如果用户选择是,则会出现另一个字段:
If user selects, No, nothing happens. If user selects Yes, there would be another field which will as:
选择格式类型: o HTML o PHP o Javascript
Select formatting type: o HTML o PHP o Javascript
我正在使用 https://toddmotto.com/angular-dynamic-components-forms 生成表单的方式,我们将设置传递给 FormGroup 并生成表单.
I'm using https://toddmotto.com/angular-dynamic-components-forms way for generating form, where we pass the settings to FormGroup and it generates a form.
我尝试的方式:
this.form.valueChanges
.subscribe(values => {
if(value['require_formatting'] === 'yes') {
this.form.addControl('formatting_type', myFormControl); // Add new form control
}
});
不幸的是,这给了我最大调用堆栈大小超出错误.当我在添加表单控件之前添加 setTimeout 时,它运行良好,但随后控制台因无限数量的不必要调用而变得混乱.
This is unfortunately, giving me "Maximum call stack size exceeded error. When I add setTimeout before adding form control it works well but then console gets messy with inifinite number of unnecessary calls.
推荐答案
试着把代码改成这样:
this.form.valueChanges
.subscribe(values => {
if(value['require_formatting'] === 'yes' && this.form.get('formatting_type')) {
this.form.addControl('formatting_type', myFormControl); // Add new form control
}
});
它应该通过只运行一次 if 语句中的代码来消除堆栈溢出.
It should get rid of the stack overflow by only running the code in the if statement once.
问题在于 if 语句中的代码在无限循环中调用 observable 的 next 函数.这样它就会运行有限的次数.
The issue is the code inside the if statement calls the observable's next function in an infinite loop. This way it will be run a finite number of times.
这篇关于Angular 5 - 如何在表单值更改时添加条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!