I've encountered an issue with a utility component I developed called the "error display component." This component is designed to handle errors in a generic way.
export class ShowErrorComponent {
// path refering to the form-element
@Input('path') controlPath = '';
@Input('name') formName = '';
constructor(private ngForm: NgForm) {}
get errorMessages(): string[] | null {
const form = this.ngForm.form;
const control = form.get(this.controlPath);
if (!control || !control.touched || !control.errors) {
return null;
}
return this.getDisplayMessages(control.errors);
}
....
}
I'm using the ShowErrorComponent in two forms. One form uses the template-driven approach while the other uses the reactive approach. The error display works as expected in the template-driven form, but when used in the reactive form, I encounter the following error:
ERROR NullInjectorError: R3InjectorError(AppModule)[NgForm -> NgForm -> NgForm]:
NullInjectorError: No provider for NgForm!
at NullInjector.get (core.mjs:6359:27)
at R3Injector.get (core.mjs:6786:33)
at R3Injector.get (core.mjs:6786:33)
at R3Injector.get (core.mjs:6786:33)
at ChainedInjector.get (core.mjs:13769:36)
at lookupTokenUsingModuleInjector (core.mjs:3293:39)
at getOrCreateInjectable (core.mjs:3338:12)
at Module.ɵɵdirectiveInject (core.mjs:10871:12)
at NodeInjectorFactory.ShowErrorComponent_Factory [as factory] (show-error.component.ts:9:32)
at getNodeInjectable (core.mjs:3523:44)
The error-component is being called within the context of the following HTML snippet:
<form
novalidate
class="register-form"
(ngSubmit)="registerMember(registerForm.value)"
[formGroup]="registerForm"
>
<div formGroupName="personalInfo">
<div class="form-group">
<h3>Personal info:</h3>
<div class="input-group mb-3">
<label class="input-group-text" for="gender">Gender</label>
<select class="form-select" id="membership" formControlName="gender">
<option value="diverse">Diverse</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<app-show-error name="Gender" path="personalInfo.gender"></app-show-error>
...
</div>
...
</div>
</div>
The registerForm variable refers to my FormGroup and is initialized inside the constructor, rendering correctly when <app-show-error>
is commented out.
Here is the relevant code snippet for the component associated with the preceding HTML snippet:
constructor(fb: FormBuilder) {
this.registerForm = fb.group({
personalInfo: fb.group({
gender: ['diverse'],
firstname: ['', [Validators.required]],
lastname: ['', [Validators.required]],
birthdate: [new Date(), [Validators.required]]
}),
...
}
I have already added ReactiveFormsModule to my Register module. My question is, why am I encountering this error?