我正在以 angular 创建表单验证,但出现错误
<块引用>未找到带有 exportAs 'ngModel' 的指令。
我的代码:
<form>
<div class="form-group">
<label for="firstname">First Name</label>
<input type="text" id="name" name="name" required minlength="4"
appForbiddenName="bob" ngModel #name="ngModel">
<div class="alert alert-danger" *ngIf>First name required</div>
</div>
<div class="form-group">
<label for="comment">Comment</label>
<textarea name="" id="comment" cols="30" rows="10" class="form-control"></textarea>
</div>
<button class="btn btn-primary">Submit</button>
</form>
错误:
Error: src/app/app.component.html:6:60 - error NG8003: No directive found with exportAs 'ngModel'.
6 appForbiddenName="bob" ngModel #name="ngModel">
~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
组件AppComponent的模板出错。
答案 0 :(得分:1)
每当您遇到此类错误时,请确保您已在主模块中导入了 forms module
。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; // <== add the imports!
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
// other components here
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
查看here了解更多详情。
答案 1 :(得分:0)
如果您使用 Angular 模板驱动的表单并希望使用 #name="ngModel" 您还需要在同一输入中使用 [(ngModel)]="mymodel" 指令,当然, 添加 import { FormsModule } from '@angular/forms';到您的 app.module.ts 和导入数组中,您需要添加 FormsModule。