Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renderer is deprecated as a favor for renderer2, alternative for `invokeElementMethod`?

For a side project of mine, I want to implement a chat stream where new message is added to the bottom and the windows should scroll to the bottom to display the latest message.

In order to do that, I have opted to use ViewChildren on the component to find the last message(latest) and use scrollIntoView on the nativeElement.

In order not to call the method by accessing the DOM API directly nativeElement.scrollIntoView(). I believe I will need to use renderer.invokeElementMethod(nativeElement, 'scrollIntoView').

Problem is renderer is deprecated in favor of renderer2 and I cant seem to find alternative for the method invokeElementMethod in renderer2.

Question is, is there a method that I missed in renderer2 that do just that? or we have a new way doing invoking element method now?

like image 558
endyjasmi Avatar asked Apr 13 '17 12:04

endyjasmi


People also ask

Is Renderer2 deprecated?

The Renderer class has been marked as deprecated since Angular version 4. This section provides guidance on migrating from this deprecated API to the newer Renderer2 API and what it means for your app.

Why would you use renderer methods instead of using native element methods?

Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break). ElementRef is a class that can hold a reference to a DOM element. This is again an abstraction to not break in environments where the browsers DOM isn't actually available.

When should I use renderer 2?

The Renderer2 allows us to manipulate the DOM elements, without accessing the DOM directly. It provides a layer of abstraction between the DOM element and the component code. Using Renderer2 we can create an element, add a text node to it, append child element using the appendchild method., etc.

What is renderer in Angular?

The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly.


1 Answers

You can use selectRootElement method of Renderer2.

For example:

constructor(private renderer: Renderer2) {}

this.renderer.selectRootElement('#domElementId').scrollIntoView()

, where domElementId is id='domElementId' in your html


UPDATE

Supply a Second Argument for selectRootElement as per Angular's Official Documentation as it is used to preserve your content

selectRootElement(selectorOrNode: any, preserveContent?: boolean): any

this.renderer
  .selectRootElement'#domElementId', true)  // Supply true for the 2nd arg to make sure your content is preserved.
  .scrollIntoView()                      // Or ({ behavior: 'smooth' }) for smooth scrolling
like image 191
seytzhan Avatar answered Oct 02 '22 12:10

seytzhan