【问题标题】:No directive found with exportAs 'ngModel'. Angular 12没有找到 exportAs 'ngModel' 的指令。角 12
【发布时间】:2023-08-26 15:21:01
【问题描述】:

我正在用 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的模板出现错误。

【问题讨论】:

    标签: angularjs angular typescript angular12


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案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 { }
      

      查看here了解更多详情。

      【讨论】:

      • 如果有帮助,您可以接受并投票。我们都会因此而得到回报!