0
votes

I'm curious if it's possible to use the myForm.controls property in an Angular Reactive form instead of defining an AbstractControl for every instance?

This method is suggested in NG-Book but it's not used with nested forms and FormGroupName.

Here is my code.

HTML:

<form [formGroup]="myForm"
    (ngSubmit)="onSubmit(myForm.value)">
<div>
  <input type="text"
         id="nameInput"
         placeholder="Product"
         [formControl]="myForm.controls['name']">
   <div *ngIf="myForm.controls['name'].hasError('required')">Name is 
   required</div>
</div>
<div formGroupName="address">
  <input type="text"
         id="streetInput"
         placeholder="Enter Street"
         [formControl]="myForm.controls['street']">
   <div *ngIf="myForm.controls['street'].hasError('required')">Street is required</div>
</div>
<button type="submit" class="ui button">Submit</button>

JS:

export class App {
  myForm: FormGroup;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'name':  ['', Validators.required],
      'address': fb.group({
        'street': ['', Validators.required],
      });
    } 
  }
}

I realize I can set formControlName="street" on the input but then I think I would have to use AbstractControl to determine it's validation state. Where as in my non-nested formGroup, I can just use myForm.controls['name'].hasError('required').

1

1 Answers

0
votes

I don't know, i understand your question well.

Do you want to get validation about nested from control?

Then, you can get myForm.get('address').control['street'].hasError('required') or myForm.get('address').get('street').hasError('required')

And you can change hasError('required') to errors.required.

These link is description about form validation.

https://angular.io/api/forms/FormGroup#example-4

https://angular.io/guide/form-validation#reactive-form-validation

If I misunderstand your question, comment.