我被链接到另一张票。此错误仅在测试中发生,我已导入每个链接消息的FormsModule。我正在使用Angular 2.2.1。
未在'ng test'中定义的ngModel我已导入FormsModule和ReactiveFormsModule无效。我一直在研究这个问题24个小时,而且我没有接近。大多数都与升级有关,我擦除并重新启动同样的问题,使用ng generate创建时,测试模板非常简单。
我使用angular cli来构建我的应用程序(并重建它......)并且我添加了表单import,因为它看起来很重要。
这是我的简单模板,请注意,它不是一个表单,而是一个div,它没有区别。 'ng serve'看似合理,所以代码在理论上是正确的。
这是我的表格......
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for='line1'>Address 1</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Line 1" id='line1' [(ngModel)]='address.line1' required>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label" for='line2'>Address 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="line2" placeholder="Line 2" [(ngModel)]='address.line2'>
</div>
</div>
<div class="form-inline">
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label" for='Suburb'>Suburb</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="suburb" placeholder="Suburb" [(ngModel)]='address.suburb'>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="State" placeholder="State" [(ngModel)]='address.state'>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" [(ngModel)]='address.postcode'>
</div>
</div>
</div>
</form>
这是我的测试规范,经过大量研究后我添加了CommonModule和ReactiveFormsModule以及FormsBuilder,没有任何乐趣。
/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { AddressComponent } from './address.component';
import { Address } from './address';
describe('Component: Address', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AddressComponent],
imports: [CommonModule, ReactiveFormsModule],
providers: [FormBuilder]
});
});
it('should create an instance', () => {
let component = new AddressComponent();
expect(component).toBeTruthy();
});
it('should handle address', () => {
expect(true).toBeTruthy();
});
});
这是我的组件。很简单......
import { Input, Component, OnInit } from '@angular/core';
import { Address } from './address';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css'],
})
export class AddressComponent implements OnInit {
@Input() address: Address;
constructor() { }
ngOnInit() {
}
}
我得到的错误是:
"): AddressComponent@4:78
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("iv class="col-sm-10">
<input type="text" class="form-control" id="line2" placeholder="Line 2" [ERROR ->][(ngModel)]='address.line2'>
答案 0 :(得分:4)
同时添加FormsModule
imports: [CommonModule, ReactiveFormsModule, FormsModule],