Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there typescript definition for DOM nativeElement?

Tags:

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

like image 465
Dainius Lukša Avatar asked Dec 08 '16 12:12

Dainius Lukša


People also ask

How do I declare ElementRef?

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.

Can we access DOM element inside angular component constructor method?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }

Why do we use ElementRef in angular?

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.


1 Answers

You need to cast. Because of the multi-platform strategy, they didn't specify a specific type for nativeElement:

(myComponentFixture.nativeElement as HTMLElement).... 
like image 139
Günter Zöchbauer Avatar answered Oct 12 '22 23:10

Günter Zöchbauer