HTML
<form [formGroup]="newMovieForm">
<ng-container formArrayName="actors">
<ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index">
<div [formGroupName]="i">
<input type="text" placeholder="First Name" formControlName="firstName" required>
<span *ngIf="newMovieForm.controls['actors']?.get(i).controls['firstName'].errors?.['hasSpaces']">>
Field is required!
</span>
TS Main Form Group
this.newMovieForm = this.fb.group({
// This are known as controls
movieName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
yearOfRelease: ['', [Validators.required]],
description: ['', [Validators.required]],
rentalCost: ['', [Validators.required, CustomValidators.onlyNumbersAllowed]],
imageUrl: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
actors: this.fb.array([]),
userReviews: this.fb.array([])
})
TS Add-on Form Group
addActor() {
const actor = this.fb.group({
firstName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
lastName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
gender: ['', [Validators.required]],
age: ['', [Validators.required]],
imageUrl: ['', [Validators.required, CustomValidators.noSpaceAllowed]]
});
this.actors.push(actor);
}
I am try to access the firstName.validators of the actor formGroup so I can display a specific error if the user does not fulfil certain criteria. I am confused about two things:
*ngIf="newMovieForm.controls['actors']?.get(i).controls['firstName'].errors?.['hasSpaces']
I am not sure if the above statement is correct in checking if the specific field is valid
If the above statement is correct. I can't seem to get rid of the Object is possibly "null" or "undefined" despite using ? or null checks like
*ngIf=" i !== null && i ! == undefined"
I do not wish to turn off strict mode, is there a way i can fix this issue.
CodePudding user response:
<ng-container formArrayName="actors">
<ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index">
<div [formGroupName]="i">
<input type="text" placeholder="First Name" formControlName="firstName" required>
<span *ngIf="newMovieForm.hasError('hasSpaces','actors.' i '.firstName')">>
Field is required!
</span>