angular2 testing: Can't bind to 'ngModel' since it isn't a known property of 'input'
Solution 1
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.
Solution 2
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;
}
Comments
-
beewest over 2 years
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'); })); });
-
Pete B. about 7 yearsThis angular stuff seems so random. Thank you for your help.
-
Adam Hughes over 6 yearsAgreed, @PeteB. Dependency injection is so great.... it does everything for you automagically... JUST DONT FORGET TO IMPORT HERE AND NO_ERROR_SCHEMA and yada yda...
-
BlockchainDeveloper over 5 yearsThis got rid of my error, but it hangs in Karma and doesn't continue creating the other components after. It is stuck now with no error.
-
kiss-o-matic almost 4 yearsThis saved me a ton of time. All of these quirks in Angular test beds. Driving me nuts.