这是一个关于如何解决 "ngModel "无法绑定的简短教程,因为它不是 "input "的已知属性。
在Angular应用程序中,当你在输入组件中添加ngModel 指令时,你会得到这个错误,而ngModel是用于从组件到模板的双向数据绑定。
下面是一个例子,在点击按钮时读取输入的文本值。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
username: string = '';
clickme() {
console.log('it does nothing',username);
}
}
app.component.ts
{{username}}
Clickme
以下是在Angular应用程序中处理表单输入文本字段时发生的错误
Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’.
This is a common error during 2-way data binding integrated using ngModel in input elements.
Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
由于ngModel不是输入的已知属性,所以不能绑定到ngModel,这个问题如何解决?
在应用程序中,如果你使用双向绑定,你必须包括以下东西来解决它。以下是不同的东西。
缺少FormModule
-
原因是ngModel在NgModule范围内不可用。
-
将
FormsModule模块导入应用模块,告诉NgModule ngModel是可用的。import { FormsModule } from '@angular/forms'; -
打开app.module.ts,改变下面的内容
imports: [ BrowserModule, ], ```markup - to ```markup imports: [ BrowserModule, FormsModule ],
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
NgModel属性的拼写检查请确保语法正确定义ngModel属性 -[(ngModel)] 并且还要仔细检查拼写,以及在Component中声明的变量。
导入ReactiveModule如果你使用的是反应式表单,请导入ReactiveModule客栈,以解决这个问题。
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
对于懒惰加载的模块
如果你的应用程序使用懒惰加载模块,你必须在每个子模块中导入FormsModule ,ReactiveFor`msModule而不是父模块(app.module.ts)。
总结
在本教程中,学习了多种方法来解决
- 在应用模块中导入formModule以实现双向绑定。
- 检查ngModel绑定的语法
- 在反应式表单的情况下导入反应式模块
- 为了解决懒惰加载模块的问题,在子模块而不是父模块中导入这些模块。