Angular 4模板解析错误:无exportAs设为ngModel的指令问题
Let's break down what's going wrong and how to fix it quickly:
Why This Error Happens
You're trying to use #email="ngModel" to reference the ngModel directive for validation, but you haven't actually added the ngModel directive to your input element. That exportAs: "ngModel" label is tied directly to the ngModel directive—without attaching ngModel to the input, Angular has no idea what directive you're trying to point to with that template variable.
The Simple Fix
You need to add either [(ngModel)] (for two-way data binding) or [ngModel] (one-way binding) to your email input. Even if you don't need to bind the value to a component property right now, you still need to include this directive to enable the validation and template variable features you're trying to use.
Updated Code Example
Here's your corrected email input section:
<form #varSubmit="ngForm" (ngSubmit)="onSubmit(varSubmit)" novalidate> <div> <!-- Add [ngModel] (or [(ngModel)] for two-way binding) to attach the directive --> <input type="email" name="emailId" placeholder="Email" #email="ngModel" [ngModel]="''" <!-- Empty initial value works if you don't need a component property --> [ngModelOptions]="{updateOn: 'change'}" required <!-- Add this to enforce the "not empty" validation --> /> </div> <div [hidden]="email.pristine || email.valid"> Email Shouldn't Be Empty...! </div> <!-- Rest of your form goes here --> </form>
One More Critical Check
Make sure you've imported FormsModule in your Angular module (like AppModule or the module holding your registration component). Without this, Angular won't recognize ngModel or ngForm at all:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // Your other imports (e.g., BrowserModule) FormsModule ], declarations: [ RegistrationComponent, // Other components in your module ] }) export class AppModule { }
内容的提问来源于stack exchange,提问作者user9541914




