Angular 5-如何在表单值更改上添加条件字段 [英] Angular 5 - How to add Conditional Fields on Form Value Change

查看:126
本文介绍了Angular 5-如何在表单值更改上添加条件字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我致力于应用条件字段逻辑.其中两个字段取决于它们的值.

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.

推荐答案

尝试将代码更改为以下内容:

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

应该只运行一次if语句中的代码,以消除堆栈溢出.

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

问题是if语句中的代码在无限循环中调用了可观察对象的下一个函数.这样,它将运行有限次.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆