2

I have simple form:

<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
  <input type="radio" id="enabled" formControlName="enabled"
    [value]="true" [checked]="form.controls.enabled.value == true"
    (click)="setValidators()">
  <label for="enabled">Enable</label>

  <input type="radio" id="disabled" formControlName="enabled"
    [value]="false" [checked]="form.controls.enabled.value == false"
    (click)="clearValidators()">
  <label for="disabled">Disable</label>

  <input type="text" class="form-control" id="text" formControlName="text">
  <button type="submit" 
    [disabled]="!form.valid">Save Changes</button>
</form>

and Angular component code:

ngOnInit() {
  this.buildForm();
}

buildForm() {
  this.form = this.formBuilder.group({
    text: [''],
    enabled: [false]
  });
}

clearValidators() {
  this.form.get("text").clearValidators();
  this.form.updateValueAndValidity();
}
    
setValidators() {
  this.form.get("text").setValidators([Validators.required]);
  this.form.updateValueAndValidity();
}

When I load page I have enabled = false and text='', but when I click on "Enable" radio button I expect setting validator on text field but text='' and form should be invalid and submit button will be disabled. But when I output in browser console form.valid value = true and I expect false.

What did I do wrong? How can I resolve this issue?

1

1 Answer 1

1

I think updateValueAndValidity does not propagate to the child elements. You have to call it on the form control as well:

this.form.get("text").updateValueAndValidity()

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.