Angular使用模板表单时报No directive found with exportAs 'ngModel'错误怎么解决
Angular模板表单
ngModel报错修复方案 错误原因
出现No directive found with exportAs 'ngModel'报错以及校验不生效的问题,是由模块导入链路不全、模板拼写错误、表单引用不规范三个问题共同导致的,修复步骤如下:
修复步骤
- 第一步:补全模块导入链路
你已经在PinModule中正确导入了FormsModule,但需要确认PinModule本身已经被添加到根模块AppModule的imports数组中,否则Angular无法加载FormsModule提供的ngModel指令。
示例AppModule配置:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { PinModule } from './pin/pin.module'; // 导入Pin功能模块 @NgModule({ declarations: [AppComponent], imports: [BrowserModule, PinModule], // 将PinModule加入导入列表 bootstrap: [AppComponent] }) export class AppModule { }
第二步:修正模板拼写错误
你在错误提示的判断逻辑中误将模板变量myPin写为myPinPin,会导致校验逻辑不生效。第三步:规范表单模板引用写法
表单的模板引用#f需要明确指定导出为ngForm,否则部分场景下表单校验状态无法正确获取。
修正后的完整模板代码
my-pin.component.html最终代码如下:
<div class="container"> <div class="container"> <div class="row"> <div class="col-6" id='pinInput'> <form (ngSubmit)="onSubmit()" #f="ngForm"> <label for="pin">Enter Pin</label> <input type="number" name="userPin" id="userPin" required ngModel #myPin="ngModel"> <span class="help-block" *ngIf="!myPin.valid && myPin.touched">Please enter your pin</span> <button class="btn btn-primary" type="submit" [disabled]="!f.valid">Submit</button> </form> </div> </div> </div> </div>
效果验证
修复完成后重新编译即可消除报错,当用户点击PIN输入框后失焦且未输入内容时,会自动展示错误提示,提交按钮同时处于禁用状态,符合预期需求。
内容的提问来源于stack exchange,提问作者JmanxC
相关产品推荐
相关产品推荐

