我使用的是Angular 4,我在控制台得到了一个错误:
不能绑定到ngModel,因为它不是input的已知属性
我该如何解决这个问题?
我使用的是Angular 4,我在控制台得到了一个错误:
不能绑定到ngModel,因为它不是input的已知属性
我该如何解决这个问题?
当前回答
尝试添加
模块级的ngModel
代码与上面的相同
其他回答
这是一个正确答案。 你需要导入FormsModule
首先在app.module.ts中
**
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
FormsModule,
ReactiveFormsModule ,
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
** 在app.component.spec.ts中的第二个
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
最好的问候,希望会有所帮助。
在app.module.ts中导入表单模块。
import { FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
ContactsComponent
],
imports: [
BrowserModule,HttpModule,FormsModule //Add here form module
],
providers: [],
bootstrap: [AppComponent]
})
在html中:
<input type="text" name="last_name" [(ngModel)]="last_name" [ngModelOptions]="{standalone: true}" class="form-control">
以上提到的解决这个问题的方法都是正确的。 但是如果你使用的是惰性加载,FormsModule需要导入到子模块中,因为子模块中有表单。在app.module.ts中添加它不会有帮助。
如果双向绑定不起作用,您应该验证以下内容。
在html中ngModel应该这样调用。不依赖于输入元素的其他属性
<输入[(ngModel)] = >“inputText
确保FormsModule被导入到模块文件app.modules.ts中
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent // suppose, this is the component in which you are trying to use two ay binding
],
imports: [
BrowserModule,
FormsModule,
// other modules
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
方法的声明中添加了你试图使用ngModel进行双向绑定的组件。在前面第2点中添加的代码
这就是使用ngModel使双向绑定工作所需做的所有事情,这在angular 9中都得到了验证
你的ngModel没有工作,因为它还不是你的NgModule的一部分。
你必须告诉NgModule你有权在整个应用中使用ngModel,你可以通过在app.module.ts -> imports->[]中添加FormsModule来实现。
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ FormsModule ], // HERE
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})