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')
.