I am trying to implement a multi-step Angular Reactive Form in my project. I am using Angular 19. I sought consultation from a tutorial that was written in Angular 8 though.
I am getting several parse errors. I have created a Stackblitz pen to simulate my project scenario as closely as possible. Feel free to work and edit my stackblitz.
This is the link: https://stackblitz.com/edit/stackblitz-starters-grjgagz8
If you visit the multi-step-form.component.ts under app -> components -> multi-step-form, you will see that there are errors on lines 62, 64, and 91.
If you hover over the red squibbly on the mentioned lines it shows the errors. I tried a number of things like explicitly mentioning the datatypes, but the errors still persist.
Can you help me get that StackBlitz working and display the multi-step form?
*Please study the code I used in my StackBlitz in totality so that you can understand the approach I tried to adopt. Inside the constants folder of my project structure, I have defined the JSON array for forming the steps of my multi-step form.
Aside from some issues in your original StackBlitz link such as the incorrect component file name for RecipeMultiStepComponent
, the selector name for AppComponent
For errors in Lines 62 & 64:
You can resolve this by specifying the validation based on the validator
. From my demo below, I added the validations for minLength
, maxLength
, etc.
getValidators(formField: any): Validators {
const fieldValidators: any = Object.keys(formField.validations).map(
(validator) => {
if (validator === 'required') {
return Validators[validator];
} else if (validator === 'minlength') {
return Validators.minLength(formField.validations[validator]);
} else if (validator === 'maxlength') {
return Validators.maxLength(formField.validations[validator]);
} else {
// Validation Not supported
return null;
}
}
);
return fieldValidators;
}
For the error in Line 91:
You can perform the null checking for masterForm
with this.masterForm && this.masterForm[formIndex]
getValidationMessage(formIndex: any, formFieldName: string): string {
const formErrors = (this.masterForm && this.masterForm[formIndex])?.get(
formFieldName
)?.errors;
const errorMessages =
this.currentFormContent[formIndex][formFieldName].errors;
const validationError =
formErrors && errorMessages[Object.keys(formErrors)[0]];
return validationError;
}