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

Angular ngModel绑定报错:非input已知属性,已引入FormsModule仍异常

解决Angular中“Can't bind to 'ngModel' since it isn't a known property of 'input'”错误

虽然你提到已引入FormsModule,但仍出现该错误,大概率是以下环节出了问题,逐一排查:

1. 确认FormsModule已正确注册到模块的imports数组

仅引入FormsModule是不够的,必须在@NgModule的imports数组中完成注册。检查你的Loginapp.module.ts:

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

import { LoginComponent } from './login.component';

@NgModule({
  declarations: [LoginComponent],
  imports: [
    BrowserModule,
    FormsModule, // 务必添加到此处
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [LoginComponent]
})
export class LoginappModule { }

2. 检查组件所属模块是否正确导入FormsModule

如果LoginComponent并非声明在Loginapp.module.ts的declarations数组中,而是属于其他子模块,那么对应的子模块也需要单独导入FormsModule,否则该组件无法识别ngModel指令。

3. 确保绑定ngModel的input元素带有name属性

使用[(ngModel)]时,必须给input元素指定name属性(或通过[ngModelOptions]="{name: 'xxx'}"配置),否则Angular会抛出错误。示例:

<!-- 正确写法 -->
<input type="text" [(ngModel)]="cred.UserName" name="userName" />
<input type="password" [(ngModel)]="cred.Password" name="password" />

4. 验证组件中cred实例的初始化正确性

确保LoginComponent中正确创建了Credentials实例:

import { Component } from '@angular/core';

class Credentials {
  UserName: string = '';
  Password: string = '';
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  cred: Credentials = new Credentials();
}

按以上步骤排查后,ngModel绑定的错误应该能解决。

内容的提问来源于stack exchange,提问作者Lekh Raj Awasthi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:47:41