6

I have a question:

Will using ElementRef.nativeElement to read a property value (e.g. 'scrollHeight') count as a DOM interaction and therefore break Angular Universal?

ElementRef seems to be the only way to read a property from an element: https://stackoverflow.com/a/38037240/5565132

Example:

HTML:

<div #test1></div>

TS:

@ViewChild('test1') test1: ElementRef;

ngOnInit() {
  console.log(this.test1.nativeElement.scrollHeight);
}
Community
  • 1
  • 1
orly
  • 164
  • 1
  • 7
  • Yes. Passing `this.test1.nativeElement` to a `Renderer` would be fine, but accessing any property or method of `nativeElement` won't. – Günter Zöchbauer May 18 '17 at 18:41
  • Thanks for your reply. So this means that reading a property from nativeElement is okay and won't break anything but setting it requires Renderer(2), correct? – orly May 18 '17 at 18:43
  • No, the `Renderer(2)` doesn't provide anything to read from `nativeElement` – Günter Zöchbauer May 18 '17 at 18:46
  • Okay. Are there any other ways to read a property from an element? e.g. test1 in this case? Because my app has some logic which depends on a element property value – orly May 18 '17 at 18:47
  • No. AFAIK the only thing you can do is to check if the code actually runs on the browsers UI thread and only then read otherwise skip that code. I don't know how to check that but I have seen it mentioned. – Günter Zöchbauer May 18 '17 at 18:50
  • Okay. Depending some logic on an element's property value doesn't seem like an exceptional thing to me or am I missing something? Why isn't this possible "the angular way"? Still thank you for your answers! – orly May 18 '17 at 18:54
  • When run on the server or in WebWorker the element just won't exist. The calls that update the DOM will be queued and then executed when the element is actually rendered in the browser. For read actions this would be way too complicated. – Günter Zöchbauer May 18 '17 at 20:04

0 Answers0