Reputation: 4846
I am trying to test angular2 two-way binding for control input
. Here is the error:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
The app.component.html
<input id="name" type="text" [(ngModel)]="name" />
<div id="divName">{{name}}</div>
The app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
name: string;
}
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');
}));
});
Upvotes: 131
Views: 65369
Reputation: 209062
You need to import the FormsModule
into the TestBed
configfuration.
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. This allows you to only add what is needed for the test without having unnecessary outside variables that may affect the test.
Upvotes: 271
Reputation: 153
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. Please check this link:
In summary i had used [value] to bind the model for the text field like this.
([value])="searchTextValue"
Also,if you are using date field you need to bind the model in ts. in the html, call the method
(dateSelect)="onDateSelect($event)"
In the type script, use the following code.This is applicable only if you are using Ngbdate picker.
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;
}
Upvotes: 1