Search code examples
javascriptangulartypescriptformgroupsangular-formbuilder

Can't validate a required field in Angular form builder form group after adding a value


Here's my stackblitz

When I click on my button (in Stackblitz link) and push a value to the array, I'd like to have the field be valid, but it's remaining invalid. If I hard code in a value, it shows as valid, but not if I push a value from a click event.

QUESTION - Can anyone help me understand why? Do I need to use some sort of formArray type?

Here is my code.

registerForm: FormGroup;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
  this.registerForm = this.formBuilder.group({
    practicedStyles: [[], [Validators.required]]
  });
}

get practicedStyles() {
  return this.registerForm.get('practicedStyles');
}

add() {
  this.practicedStyles.value.push(1);
}
<div class="card m-3">
  <h5 class="card-header">Angular 8 Reactive Form Validation</h5>
  <div class="card-body">
    <form [formGroup]="registerForm">
      <p>Is valid: {{practicedStyles.valid}}</p>
      <p>Is required: {{practicedStyles.errors?.required}}</p>
      <button class="btn btn-primary" (click)="add()">Add</button>
    </form>
  </div>
</div>


Solution

  • Did you try using FormGroup.setValue?

        add() {
          this.registerForm.get('practicedStyles').value.push(1);
          this.registerForm.setValue({practicedStyles: this.registerForm.get('practicedStyles').value});
        }
    

    I think pushing the value directly to the array wouldn't trigger the change because you're not changing the object's reference. And if you try to reassign the FormGroup control to a new object: this.practicedStyles.value = 1 you'll get the following errro message Cannot assign to 'value' because it is a read-only property.

    When manipulating FormGroup controls you should use the FormGroup provided methods to do so:

    So even though you are not changing the object's reference, you are notifying the framework that the object did change.