I am testing an Angular2 component and want to assert nativeElement's property of the component, but there is no typescript definition for it. My test looks like this:
beforeEach( () => { myComponentFixture = TestBed.createComponent(MyComponent); myComponent = myComponentFixture.componentInstance; }); it('Should display something', fakeAsync(() => { myComponentFixture.detectChanges(); expect(myComponentFixture.nativeElement.textContent).toContain('something'); }));
The problem is that after i type nativeElement.
there is not IntelliSense for it because I think there are no typings for nativeElement. There are more properties which I may want to check like innerHtml, id, etc. This example test may not make sense, but I may test some specific DOM element's properties using myComponentFixture.debugElement.query(By.css('#myElement')).nativeElement
Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.
You need to cast. Because of the multi-platform strategy, they didn't specify a specific type for nativeElement
:
(myComponentFixture.nativeElement as HTMLElement)....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With