-1

我正在以角度创建表单验证,但出现错误

没有找到 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 的模板出现错误。

4

2 回答 2

2

每当您收到此类错误时,请确保您已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 { }

在这里查看更多详情。

于 2021-06-09T05:37:09.053 回答
2

如果您使用 Angular 模板驱动的表单并想使用 #name="ngModel" 您也可以need to use [(ngModel)]="mymodel" directive in the same input,当然,

Add import { FormsModule } from '@angular/forms';

app.module.ts需要在导入数组中添加 FormsModule。

于 2021-06-09T05:37:33.513 回答