问题
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