[英]angular2 testing: Can't bind to 'ngModel' since it isn't a known property of 'input'
I am trying to test angular2 two-way binding for control input
.我正在尝试测试控制
input
angular2 双向绑定。 Here is the error:这是错误:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
The app.component.html app.component.html
<input id="name" type="text" [(ngModel)]="name" />
<div id="divName">{{name}}</div>
The app.component.ts app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
name: string;
}
app.component.spec.ts app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('App: Cli', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers:[AppService]
});
});
it('divName', async(() => {
let fixture = TestBed.createComponent(AppComponent);
let comp = fixture.componentInstance;
comp.name = 'test';
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('divName').textContent).toContain('test');
}));
});
You need to import the FormsModule
into the TestBed
configfuration.您需要将
FormsModule
导入到TestBed
配置中。
import { FormsModule } from '@angular/forms';
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [
AppComponent
],
providers:[AppService]
});
What you are doing with the TestBed
is configuring a NgModule from scratch for the test environment.您使用
TestBed
是从头开始为测试环境配置 NgModule。 This allows you to only add what is needed for the test without having unnecessary outside variables that may affect the test.这允许您只添加测试所需的内容,而不会添加可能影响测试的不必要的外部变量。
I had the same issue, even after importing forms module this was not solved.我有同样的问题,即使在导入表单模块后也没有解决。 So I had to use alternative to ngModel for text field.
所以我不得不在文本字段中使用 ngModel 的替代品。 Please check this link :
请检查此链接:
In summary i had used [value] to bind the model for the text field like this.总之,我使用 [value] 来绑定文本字段的模型,如下所示。
([value])="searchTextValue"
Also,if you are using date field you need to bind the model in ts.此外,如果您使用日期字段,则需要在 ts 中绑定模型。 in the html, call the method
在html中,调用方法
(dateSelect)="onDateSelect($event)"
In the type script, use the following code.This is applicable only if you are using Ngbdate picker.在类型脚本中,使用以下代码。这仅在您使用 Ngbdate 选择器时适用。
onDateSelect(event) {
let year = event.year;
let month = event.month <= 9 ? '0' + event.month : event.month;;
let day = event.day <= 9 ? '0' + event.day : event.day;;
let finalDate = year + "-" + month + "-" + day;
this.finalDateVlaue = finalDate;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.