So I'm trying to add a simple validation message.
App.Module.ts
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
...
imports: [ FormsModule, ReactiveFormsModule, ]
})
HTML
<div class="form-group">
<label>Nickname</label>
<input type="text" class="form-control"
id="nickname" formControlName="nickname"
[(ngModel)]="MyProfileForm.nickname" name="nickname" #nickname="ngModel">
<div [hidden]="nickname.valid" class="alert alert-danger">Nickname is required.</div>
</div>
.ts
import { FormBuilder, FormControl, FormGroup, Validators, FormsModule, NgModel } from "@angular/forms";
export class MyProfileComponent
{
constructor(private fbdr: FormBuilder) { }
People = ...;
MyProfileForm: FormGroup;
this.MyProfileForm = this.fbdr.group
(
{
nickname: new FormControl(this.People.selfnickname, [Validators.required, Validators.minLength(4)])
}
);
}
I've tried all answers of this SO.
Full stack from console:
core.js:6210 ERROR Error: Uncaught (in promise): Error: NG0301: Export of name 'ngModel' not found!. Find more at https://angular.io/errors/NG0301 Error: NG0301: Export of name 'ngModel' not found!. Find more at https://angular.io/errors/NG0301 at cacheMatchingLocalNames (core.js:10393) at resolveDirectives (core.js:10224) at elementStartFirstCreatePass (core.js:14786) at ɵɵelementStart (core.js:14823) at MyProfileComponent_Template (template.html:21) at executeTemplate (core.js:9614) at renderView (core.js:9418) at renderComponent (core.js:10698) at renderChildComponents (core.js:9283) at renderView (core.js:9443) at resolvePromise (zone.js:1209) at resolvePromise (zone.js:1163) at zone.js:1275 at ZoneDelegate.invokeTask (zone.js:402) at Object.onInvokeTask (core.js:28578) at ZoneDelegate.invokeTask (zone.js:401) at Zone.runTask (zone.js:174) at drainMicroTaskQueue (zone.js:578) at ZoneTask.invokeTask [as invoke] (zone.js:487) at invokeTask (zone.js:1596)
Concern
There are some issues in your attached code that make the project unable to compile. Be sure you review and provide a Minimal, Reproducible Example.
Solution: Angular Template Driven Form
For Template Driven Form, you need to remove
formControlNamefrominputelement.Meanwhile, found out that you miss out
requiredattribute in theinputelement that leads to the error message unable to be displayed.And remove all related Reactive Form code if you prefer for Template Driven Form.
Solution: Angular Template Driven Form on StackBlitz
Solution: Angular Reactive Form
For the Reactive form, you should remove
[(ngModel)]fromFormControlas it is deprecated.Solution: Angular Reactive Form on StackBlitz
Would suggest Angular Reactive Form documentation as a great resource for you can to follow the instructions and guidelines while creating your form.