协慌网

登录 贡献 社区

无法绑定到'ngModel',因为它不是'input' 的已知属性

启动 Angular 应用程序时出现以下错误,即使未显示该组件也是如此。

我必须注释掉,以便我的应用程序正常运行。

zone.js:461 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("
    <div>
        <label>Created:</label>
        <input  type="text" [ERROR ->][(ngModel)]="test" placeholder="foo" />
    </div>
</div>"): InterventionDetails@4:28 ; Zone: <root> ; Task: Promise.then ; Value:

我正在看着英雄的掠夺者,但我没有看到任何区别。

这是组件文件:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Intervention } from '../../model/intervention';

@Component({
    selector: 'intervention-details',
    templateUrl: 'app/intervention/details/intervention.details.html',
    styleUrls: ['app/intervention/details/intervention.details.css']
})

export class InterventionDetails
{
    @Input() intervention: Intervention;

    public test : string = "toto";
}

答案

是的,就是它,在 app.module.ts 中,我刚刚补充说:

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

为了能够对表单输入使用双向数据绑定,您需要在Angular模块中导入FormsModule包。有关更多信息,请参阅此处Angular 2官方教程和表单的官方文档

对于在Angular 2,45 + 中使用[(ngModel)] ,您需要从 Angular 形式导入FormsModule ...

它也是在github中 Angular repo 中的表单下的这条路径中:

angular / packages / forms / src / directives / ng_model.ts

可能这对AngularJs 开发人员来说并不是一件非常愉快的事情,因为你可以随时随地使用ng-model ,但是当 Angular 尝试将模块分开以使用你想要的任何东西时, ngModel现在在FormsModule 中

此外,如果您使用ReactiveFormsModule,也需要导入它。

所以只需查找app.module.ts并确保您已导入FormsModule ...

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';  //<<<< import it here
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule //<<<< and here
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

这也是ngModelAngular4 ngModel的当前起始注释:

/**
 * `ngModel` forces an additional change detection run when its inputs change:
 * E.g.:
 * ```
 * <div>{{myModel.valid}}</div>
 * <input [(ngModel)]="myValue" #myModel="ngModel">
 * ```
 * I.e. `ngModel` can export itself on the element and then be used in the template.
 * Normally, this would result in expressions before the `input` that use the exported directive
 * to have and old value as they have been
 * dirty checked before. As this is a very common case for `ngModel`, we added this second change
 * detection run.
 *
 * Notes:
 * - this is just one extra run no matter how many `ngModel` have been changed.
 * - this is a general problem when using `exportAs` for directives!
 */

如果您想使用输入而不是表单,可以将它与ngModelOptions一起ngModelOptions并使其独立真实 ......

[ngModelOptions]="{standalone: true}"

有关详细信息, 此处查看 Angular 部分中的ng_model