You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular引入FormsModule仍报“No directive found with exportAs 'ngModel'”错误求助

Angular 15.2.9 解决“No directive found with exportAs 'ngModel'”错误

核心问题是你把FormsModule和ReactiveFormsModule错误地加到了app.module.ts的declarations数组里——declarations只用来声明组件、指令、管道,表单模块必须放在imports数组中才能生效。

正确的AppModule配置

修改app.module.ts,把表单模块移到imports里:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { FormComponent } from './form/form.component';

@NgModule({
  declarations: [
    AppComponent,
    FormComponent // 组件放在declarations里
  ],
  imports: [
    BrowserModule,
    FormsModule, // 表单模块必须在这里导入
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

如果你用的是独立组件

如果你的FormComponent是独立组件(带有standalone: true),需要在组件自身的imports数组中导入FormsModule,无需在AppModule中配置:

import { Component, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
  standalone: true,
  imports: [FormsModule] // 独立组件在这里导入表单模块
})
export class FormComponent {
  @Input('name') name : any;
  categories = [
    { id: 1, name: 'dev'},
    { id: 2, name: 'dev2'},
  ]
}

额外提示

你的HTML中select标签没有绑定ngModel,若需要双向绑定可以补充:

<select name="category" id="category" class="form-control" ngModel>
  <option value=""></option>
  <option *ngFor="let categoryName of categories" [value]="categoryName.id">{{ categoryName.name }}</option>
</select>

内容的提问来源于stack exchange,提问作者Norbert_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 01:02:43