Angular 向响应式表单添加表单控件

Angular adding form controls to reactive forms

我正在尝试在选择单选选项“是”时需要一个文本区域,但它确实可以工作

如果我选择是我得到

RangeError: Maximum call stack size exceeded

如果我选择否然后是我得到

Cannot find control with unspecified name attribute

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {SorDataService} from '../sor-data.service';

@Component({
  selector: 'app-intervention-strategies',
  templateUrl: './intervention-strategies.component.html',
  styleUrls: ['./intervention-strategies.component.css']
})
export class InterventionStrategiesComponent implements OnInit {

  public form: FormGroup;

  /** Page 5 */
  constructor(public data: SorDataService, private formBuilder: FormBuilder, private router: Router) {
  }

  public ngOnInit() {

    this.form = this.formBuilder.group({
      csc_dynamicsecurity: [null, Validators.required],
    });

    this.form.valueChanges.subscribe(values => {

      if (values['csc_dynamicsecurity'] === true) {
        this.form.addControl('csc_dynamicsecurityexplanation', new FormControl('', Validators.required)); // Add new form control
      }
      else if (values['csc_dynamicsecurity'] === false) {
        this.form.removeControl('csc_dynamicsecurityexplanation');
      }
    });
  }

  public next() {

    if (this.form.valid) {
      alert('valid');
    }
  }
}

正在尝试向有条件地添加到表单的字段添加表单验证

<form [formGroup]="form">

  <div class="app-radio-field app-field-required" [ngClass]="displayFieldCss('csc_dynamicsecurity')">

    <h5 i18n>Dynamic Security and Staff Presence?</h5>

    <mat-radio-group [formControl]="form.get('csc_dynamicsecurity')">
      <mat-radio-button color="primary" [value]="true"
                        i18n>Yes
      </mat-radio-button>

      <mat-radio-button color="primary" [value]="false"
                        i18n>No
      </mat-radio-button>
    </mat-radio-group>
  </div>

  <mat-form-field class="full-width" *ngIf="form.get('csc_dynamicsecurity').value === true">
  <textarea matTextareaAutosize matInput required i18n-placeholder placeholder="Explain"
            [formControl]="form.get('csc_dynamicsecurityexplanation')"></textarea>
  </mat-form-field>

</form>

我也尝试按照其他人的建议将 && this.form.get('csc_dynamicsecurityexplanation') 添加到订阅中,这似乎修复了堆栈错误,但我仍然收到以下错误。我不太确定我是否做对了。任何帮助都适用

Cannot find control with unspecified name attribute

    this.form.valueChanges.subscribe(values => {

      if (values['csc_dynamicsecurity'] === true && this.form.get('csc_dynamicsecurityexplanation')) {
        this.form.addControl('csc_dynamicsecurityexplanation', new FormControl('', Validators.required)); // Add new form control
      }
      else if (values['csc_dynamicsecurity'] === false && this.form.get('csc_dynamicsecurityexplanation')) {
        this.form.removeControl('csc_dynamicsecurityexplanation');
      }
    });
  }

您可以订阅 'csc_dynamicsecurity' formControl valueChanges,而不是观察 form valueChanges。那应该可以解决您的错误。在 form.valueChanges 中添加新的 formControls 可能会导致无限循环,从而导致 RangeError: Maximum call stack size exceeded

 this.form.get('csc_dynamicsecurity').valueChanges.subscribe(values => {

      if (values === true) {
        this.form.addControl('csc_dynamicsecurityexplanation', new FormControl('', Validators.required), ); // Add new form control
      }
      else if (values === false) {
        this.form.removeControl('csc_dynamicsecurityexplanation');
      }
    });
  }

看到这个工作 code

我根据@Amit 的代码想出了一个通用的解决方案,希望它能帮助到一些人

public ngOnInit() {

    this.form = this.formBuilder.group({
      csc_dynamicsecurity: [null, Validators.required],
    });

    const fnBool = (input) => {
      return (value) => {
        if (value === true) {
          this.form.addControl(input, new FormControl('', Validators.required)); // Add new form control
        }
        else if (value === false) {
          this.form.removeControl(input);
        }
      };
    };

    this.form.get('csc_dynamicsecurity').valueChanges.subscribe(fnBool('csc_dynamicsecurityexplanation'));
  }