Angular 5 - How to add Conditional Fields on Form Value Change

核能气质少年 提交于 2020-01-06 07:14:38

问题


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:

Do you want to format this code: o Yes o No

If user selects, No, nothing happens. If user selects Yes, there would be another field which will as:

Select formatting type: o HTML o PHP o Javascript

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.

Way I tried:

this.form.valueChanges
.subscribe(values => {
    if(value['require_formatting'] === 'yes') {
        this.form.addControl('formatting_type', myFormControl); // Add new form control
    }
});

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.


回答1:


Try changing the code to something like this:

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
    }
});

It should get rid of the stack overflow by only running the code in the if statement once.

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.



来源:https://stackoverflow.com/questions/48729092/angular-5-how-to-add-conditional-fields-on-form-value-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!