1

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Much thanks.. it perfect, it works like a charm. this post is what threw me off stackoverflow.com/questions/48729092/…
That solution in the link did not work for you because you missed the second condition on if. In your case, there is no reason to watch for entire form. You are just concerned about the radio form control value.
wasnt sure i needed to accept the answer thanks for pointing that out
0

I came up with a generic solution to the problem based on @Amit's code, hopeful it can help some one

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.