Angular项目[(ngModel)]绑定报错:已导入FormsModule仍未解决
问题排查与解决方法
错误含义解释
Can't bind to 'ngmodel' since it isn't a known property of 'input'.ngtsc(-998002)
Angular无法识别input标签上的ngmodel属性,因为官方提供的双向绑定指令是驼峰命名的ngModel,全小写的写法会被当作普通HTML属性,而非框架指令,因此触发该错误。
核心问题与修复步骤
1. 模板指令拼写错误(最关键)
你的模板中存在两处指令拼写不符合Angular规范:
- 所有
[(ngmodel)]需改为[(ngModel)](注意M和O大写) - 表单提交事件
(ngsubmit)需改为(ngSubmit)(Angular事件绑定遵循驼峰命名)
同时,组件模板不需要包含<html>和<!DOCTYPE html>标签,根模块的index.html已经处理了这些基础结构,可直接移除。
修改后的update-employee.component.html:
<div class="row"> <div class="card col-md-6 offset-md-3 offset-md-3"> <div class="row"> <h3 class="text-center"> Update Employee </h3> <hr /> <div class="card-body"> <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label> First Name</label> <input type="text" class="form-control" id="firstName" [(ngModel)]="employee.firstName" name="firstName"> </div> <div class="form-group"> <label> Last Name</label> <input type="text" class="form-control" id="lastName" [(ngModel)]="employee.lastName" name="lastName"> </div> <div class="form-group"> <label> Email Id</label> <input type="text" class="form-control" id="emailId" [(ngModel)]="employee.emailId" name="emailId"> </div> <br /> <button class="btn btn-success" type="submit">Submit</button> </form> </div> </div> </div> </div>
2. 移除重复的@NgModule装饰器
你的app.module.ts中存在两个@NgModule块,Angular模块仅允许一个@NgModule装饰器,重复定义会导致配置异常。删除第一个空的@NgModule块即可:
修改后的app.module.ts:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http' import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EmployeeListComponent } from './employee-list/employee-list.component'; import { CreateEmployeeComponent } from './create-employee/create-employee.component'; import { FormsModule} from '@angular/forms'; import { UpdateEmployeeComponent } from './update-employee/update-employee.component'; import { EmployeeDetailsComponent } from './employee-details/employee-details.component' import { ReactiveFormsModule } from '@angular/forms'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; @NgModule({ declarations: [ AppComponent, EmployeeListComponent, CreateEmployeeComponent, UpdateEmployeeComponent, EmployeeDetailsComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, ReactiveFormsModule, ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
3. 确保组件中employee属性已定义
在UpdateEmployeeComponent类中,需提前声明employee对象,否则双向绑定会失效:
export class UpdateEmployeeComponent { // 根据你的业务需求定义employee结构,示例如下 employee = { firstName: '', lastName: '', emailId: '' }; onSubmit() { // 实现表单提交逻辑 console.log(this.employee); } }
验证修复
完成上述修改后,重启Angular开发服务器(ng serve),错误即可消除,双向绑定功能正常工作。
内容的提问来源于stack exchange,提问作者Janvi
相关产品推荐
相关产品推荐

