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_
相关产品推荐
相关产品推荐

