Search code examples
angulartypescriptangular6angular-formsangular-validation

Angular adding form controls to reactive forms


Im am trying to have a textarea required when the the radio option Yes is choosen, but it does sort of work

if i choose Yes i get

RangeError: Maximum call stack size exceeded

if i choose No then Yes i get

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

Trying to add form validation to a field that is conditionally added to the form

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

I also tried adding && this.form.get('csc_dynamicsecurityexplanation') to the subscribe as i had sen others suggest and this seems to fix the stack error but i still get the below error .. Im not quite sure im doing this right .. any help is appriciated

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

Solution

  • Instead of observing form valueChanges, you could subscribe to 'csc_dynamicsecurity' formControl valueChanges. That should fix your errors. Adding new formControls within form.valueChanges could result in infinite loop and hence leading to 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');
          }
        });
      }
    

    See this working code