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

问题描述 投票:163回答:14

我正在尝试在Angular 2中实现Dynamic Forms。我在动态表单中添加了删除和取消等附加功能。我遵循了这个文档:https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

enter image description here

我对代码做了一些更改。我在这里得到错误。

我该怎么做这个错误?

你可以在这里找到完整的代码:http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview,它在plunker中工作但在我的本地系统中没有。

Html代码:

<div>
  <form [formGroup]="form">

    <div *ngFor="let question of questions" class="form-row">
      <label [attr.for]="question.key">{{question.label}}</label>

  <div [ngSwitch]="question.controlType">

    <input *ngSwitchCase="'textbox'" [formControlName]="question.key"
            [id]="question.key" [type]="question.type" [(ngModel)]="question.value">

    <select [id]="question.key" [(ngModel)]="question.value" *ngSwitchCase="'dropdown'" [formControlName]="question.key" >
      <option *ngFor="let opt of question.options" [ngValue]="opt.key" >{{opt.value}}</option>
    </select>

    <input *ngSwitchCase="'checkbox'"  [(ngModel)]="question.value"
            [id]="question.key" [type]="question.type" (change)="question.value = ck.checked" #ck [ngModelOptions]="{standalone: true}">

  </div> 
  <div class="errorMessage" *ngIf="!form.controls[question.key].valid">{{question.label}} is required</div>
    </div>

    <div class="form-row">
      <button type="submit" [disabled]="!form.valid" (click)="onSubmit()">Save</button>
      <button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>
      <button type="button" class="btn btn-default" (click)="clear()">Clear</button>

    </div>
  </form>

  <div *ngIf="payLoad" class="form-row">
    <strong>Saved the following values</strong><br>{{payLoad}}
  </div>
</div>

组件代码:

import { Component, Input, OnInit }  from '@angular/core';
import { FormGroup, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
import { QuestionBase }                 from './question-base';
import { QuestionControlService }       from './question-control.service';
import { ControlGroup }     from '@angular/common';
import {ChangeDetectorRef} from '@angular/core';
import { FormsModule }   from '@angular/forms';

@Component({
  selector: 'dynamic-form',
  templateUrl: 'app/dynamicform/form.component.html',
  directives: [REACTIVE_FORM_DIRECTIVES],
  providers:  [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: QuestionBase<any>[] = [];
  form: FormGroup;
  payLoad:any;
  payLoad2:any;
  questiont: QuestionBase<any>;
  questiond: QuestionBase<any>;
  constructor(private qcs: QuestionControlService, private cdr: ChangeDetectorRef) {  }
  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
    console.log("Form Init",this.questions);
    this.questiont = JSON.parse(JSON.stringify(this.questions));
    this.questiond = JSON.parse(JSON.stringify(this.questions));
  }
  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
    this.payLoad2=this.payLoad;
    this.questiont = JSON.parse(JSON.stringify(this.questions));
    console.log("Submitted data",this.questions);
  }
  cancel(){
    console.log("Canceled");
    this.questions = JSON.parse(JSON.stringify(this.questiont));
  }
  clear(){
    this.questions = JSON.parse(JSON.stringify(this.questiond));
    this.questiont = JSON.parse(JSON.stringify(this.questiond));
    console.log("Cleared");
    this.cdr.detectChanges();
  }
}
forms angular angular2-template angular2-forms
14个回答
268
投票

找出快速解决方案,更新你的@NgModule代码,如下所示:

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

@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})

export class AppModule { }

资料来源:Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’


2
投票

您需要将@ angular / forms依赖项导入模块。

如果您使用的是npm,请安装依赖项:

npm install @angular/forms --save

将其导入您的模块:

import {FormsModule} from '@angular/forms';
@NgModule({
    imports: [.., FormsModule,..],
    declarations: [......],
    bootstrap: [......]
})

如果您使用SystemJs加载模块

'@angular/forms': 'node_modules/@angular/forms/bundles/forms.umd.js',

现在您可以使用[(ngModel)]两种方式进行数据绑定。


0
投票

如果您使用Karma,这个答案可能对您有所帮助:

我完全按照@ wmnitin的回答中提到的那样做了,但错误始终存在。当使用“ng serve”而不是“karma start”时,它可以工作!


0
投票

由于Angular 6中的某些原因,只是导入FormsModule并没有解决我的问题。最后解决我的问题的是添加

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
})

export class MyClass{
}

0
投票

它在Angular教程中描述:https://angular.io/tutorial/toh-pt1#the-missing-formsmodule

您必须导入qazxsw poi并将其添加到qazxsw poi声明中的导入。

FormsModule

0
投票

我们假设,您的旧app.module.ts看起来可能类似于:

@NgModule

现在在app.module.ts中导入FormsModule

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

@NgModule({
  declarations: [
    AppComponent,
    DynamicConfigComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }


52
投票

为了在使用AppModule(NgModule)时使ngModel工作,您必须在AppModule中导入FormsModule。

像这样:

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

import { AppComponent }   from './app.component';


@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    bootstrap: [AppComponent]
})
export class AppModule {}

12
投票

升级到RC5后我遇到类似的错误;即Angular 2:无法绑定到'ngModel',因为它不是'input'的已知属性。

Plunker上的代码显示您使用Angular2 RC4,但https://angular.io/docs/ts/latest/cookbook/dynamic-form.html的示例代码使用的是NGModule,它是RC5的一部分。 NGModules是从RC4到RC5的重大变化。

本页介绍了从RC4到RC5的迁移:https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html

我希望这可以解决您所遇到的错误,并帮助您朝着正确的方向前进。

简而言之,我必须在app.module.ts中创建一个NGModule:

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

import { AppComponent }  from './app.component';

@NgModule({
    imports:      [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

然后我改变main.ts使用模块:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

当然,我还需要更新package.json中的依赖项。这是我从package.json的依赖项。不可否认,我已经从其他来源(也许是ng文档示例)中将它们混在一起,因此您的里程可能会有所不同:

...
"dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"
  },
...

我希望这会有所帮助。 :-)


9
投票
import {FormControl,FormGroup} from '@angular/forms';

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

您还应该添加缺少的那些。


7
投票

你刚刚添加FormsModule并导入你的FormsModule文件中的app.module.ts

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

imports: [
    BrowserModule, FormsModule 
],

只需在app.module.ts中添加以上两行。它工作正常。


4
投票

您需要在@NgModule装饰器中导入FormsModule,而@NgModule存在于moduleName.module.ts文件中。

import { FormsModule } from '@angular/forms';
@NgModule({
   imports: [
      BrowserModule,
      FormsModule
   ],
   declarations: [ AppComponent ],
   bootstrap: [ AppComponent ]
 })

4
投票

接下来的步骤

1. Open your app.module.ts file.

.

2. Add import { FormsModule } from '@angular/forms';

.

3. Add FormsModule to imports asimports: [ BrowserModule, FormsModule ],

.

最终结果将如下所示

.....
import { FormsModule } from '@angular/forms';
.....
@NgModule({
.....
  imports: [   
     BrowserModule, FormsModule 
  ],
.....
})

3
投票

为了能够使用'ngModule',需要将'FormsModule'(来自@angular/forms)添加到import[]中的AppModule数组中(默认情况下应该在CLI项目中)。


3
投票

首先从angular lib和NgModule导入FormsModule,在导入中声明它

import { FormsModule } from '@angular/forms';
    @NgModule({
      declarations: [
        AppComponent,
        ],
      imports: [
        BrowserModule,
        FormsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
© www.soinside.com 2019 - 2024. All rights reserved.