我使用的是Angular 4,我在控制台得到了一个错误:
不能绑定到ngModel,因为它不是input的已知属性
我该如何解决这个问题?
我使用的是Angular 4,我在控制台得到了一个错误:
不能绑定到ngModel,因为它不是input的已知属性
我该如何解决这个问题?
当前回答
在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">
其他回答
用Angular 7.x更新。X,在我的一个模块中遇到了同样的问题。
如果它在你的独立模块中,添加这些额外的模块:
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
@NgModule({
imports: [CommonModule, FormsModule], // the order can be random now;
...
})
如果它在app。module中。Ts,添加这些模块:
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ FormsModule, BrowserModule ], // order can be random now
...
})
一个简单的演示来证明这一点。
尝试添加
模块级的ngModel
代码与上面的相同
在app.module.ts中添加以下内容:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [FormsModule],
})
在我的例子中,在我的应用程序的惰性加载转换期间,我在app-routing.module.ts中错误地导入了RoutingModule而不是ComponentModule
以上提到的解决这个问题的方法都是正确的。 但是如果你使用的是惰性加载,FormsModule需要导入到子模块中,因为子模块中有表单。在app.module.ts中添加它不会有帮助。