3

I have just learnt that the keyword "nativeElement" is not cross browser compliant, e.g.:

let whatever = <HTMLDivElement>this.$elementRef.nativeElement;
whatever.style.display = 'none';

which is now corrected by using the render method like so.

this._render.setElementClass(whatever, 'display', 'none');

However I also have the following:

this.whatever = <HTMLDivElement>this.$elementRef.nativeElement.querySelector(".myLookupClass");

Please advise if in this instance

".nativeElement.querySelector(".myLookupClass")" works cross browser? If not please advise an alternative technique.

Thanks in advance.

fool-dev
  • 7,671
  • 9
  • 40
  • 54
vicgoyso
  • 636
  • 1
  • 14
  • 35

2 Answers2

2

Your code will work on cross browser. First you need to understand what actually gives angular to you when you write following code:

this.$elementRef.nativeElement

Angular will give you the reference of your component which rendered on DOM. It means Angular gives a plain javascript object and you can play with this object at any browser. SO go ahead and use your code. This will be supported on any browser.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15
1

nativeElement is not related to "cross-browser", but to "cross-platform" where "platform" is DOM thread, Web Worker thread, server side-rendering, ...

If you want to utilize Web Worker features provided by Angular, or server side rendering (Angular Universal), you should or need to avoid accessing any properties or methods of nativeElement. Passing nativeElement around (like to Renderer2 methods is fine though).

As mentioned in the other answer, the nativeElement returns the DOM element and this won't be available in platforms that are not the browsers DOM thread.

If your application only utilizes the browsers DOM thread, there is no specific benefit of avoiding access to nativeElement... properties and methods except that preventing you from utilizing other platforms later.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks, I want it working for mobile and other devices therefore so I will refrain from using nativeElement. – vicgoyso Jan 08 '18 at 12:10
  • I don't think it's related to mobile, but I don't know how Ionic uses Angular. – Günter Zöchbauer Jan 08 '18 at 12:11
  • 1
    Then you should search for Ionic-specific information to `nativeElement`. My answer is only for the general case. I just googled a bit and it doesn't look like Ionic prevents use of `nativeElement`. Just start testing early on the Ionic platform then you'll know for sure. – Günter Zöchbauer Jan 08 '18 at 12:14