首页 > 解决方案 > Angular:无法绑定到“ngModel”,因为它不是“输入”的已知属性(不是重复)

问题描述

我在这里阅读了很多关于同一主题的帖子,但我 99% 确信我已经遵守了所有答案。从 ng new 为您创建的非常基本的应用程序开始。它运行良好,通过了 3 个 Karma 测试。我使用 ngModel 添加了一个带有一个输入 <==> typescript 链接的新组件,它无法测试新组件并出现以下错误:

Failed: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("<div class="boxed">
    <b>Invoice:</b>
      <input [ERROR ->][(ngModel)]= "qty">
    </div>
 "): ng:///DynamicTestModule/CalculateComponent.html@2:11
Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("<div class="boxed">
  <b>Invoice:</b>
    <input [ERROR ->][(ngModel)]= "qty">
</div>
 "): ng:///DynamicTestModule/CalculateComponent.html@2:11
    at syntaxError (./node_modules/@angular/compiler/fesm5/compiler.js?:1275:17)
    at TemplateParser.parse (./node_modules/@angular/compiler/fesm5/compiler.js?:15084:19)
    at JitCompiler._parseTemplate (./node_modules/@angular/compiler/fesm5/compiler.js?:24272:37)
    at JitCompiler._compileTemplate (./node_modules/@angular/compiler/fesm5/compiler.js?:24259:23)
    at eval (./node_modules/@angular/compiler/fesm5/compiler.js?:24202:62)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (./node_modules/@angular/compiler/fesm5/compiler.js?:24202:19)
    at eval (./node_modules/@angular/compiler/fesm5/compiler.js?:24120:19)
    at Object.then (./node_modules/@angular/compiler/fesm5/compiler.js?:1266:77)
    at JitCompiler._compileModuleAndAllComponents (./node_modules/@angular/compiler/fesm5/compiler.js?:24118:26)

我已经从 '@angular/forms' 导入 { FormsModule };和导入:[ FormsModule ] 我正确拼写了 ngModel。接下来我会发布文件。

请帮忙。

app.module.ts

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

import { AppComponent } from './app.component';
import { CalculateComponent } from './calculate/calculate.component';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here

@NgModule({
  declarations: [
    AppComponent,
    CalculateComponent
  ],
  imports: [
    FormsModule,
    BrowserModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts 两个版本,一个有表单内容,一个没有表单内容。不要认为它应该在那里,但也试了一下。 版本 1:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'testKarma';
}

V2

import { Component } from '@angular/core';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 

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


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

export class AppComponent {
  title = 'testKarma';
}

app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { CalculateComponent } from './calculate/calculate.component';  //klf
import { FormsModule } from '@angular/forms'; 
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CalculateComponent  
      ],
      imports: [ FormsModule ] 
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'testKarma'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('testKarma');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to testKarma!');
  }));
});

app.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<div>
  <app-calculate></app-calculate>  
</div>

计算.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-calculate',
  templateUrl: './calculate.component.html',
  styleUrls: ['./calculate.component.css']
})
export class CalculateComponent implements OnInit {

  qty = 0;  

  constructor() { }

  ngOnInit() {
  }
}

计算.component.html

<div class="boxed">
  <b>Invoice:</b>
    <input [(ngModel)]= "qty">
</div>

计算.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CalculateComponent } from './calculate.component';

describe('CalculateComponent', () => {
  let component: CalculateComponent;
  let fixture: ComponentFixture<CalculateComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CalculateComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CalculateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

标签: angularjasminengmodel

解决方案


@dmcgrandle 为我找到的简短答案。(谢谢!!)

我的主要组件 app.component.html 包含一个依赖组件

<app-calculate></app-calculate>  

我已经为 ngModel 添加了这些需要的行以在 app.component.ts 中工作

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

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

当我运行该应用程序时,计算组件从我将其添加到我的 app.component 中继承了表单,并且它工作得很好。但是当我运行 ng test 时,它会失败,因为测试是单独运行的,所以计算组件无法使用 ngModel。解决方法是在 calculate.component.spec.ts 中包含表单

import { FormsModule } from '@angular/forms'; 
...
 beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule ],  
      declarations: [ CalculateComponent ]
    })
    .compileComponents();
  }));

推荐阅读