Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

angular2 directives - Difference between Renderer and ElementRef in angular 2

What is the difference between Renderer and ElementRef? In Angular both are used for DOM Manipulation. I am currently using ElementRef alone for writing Angular 2 directives. If I get more info about Renderer, I can use that in my future directives.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Renderer is a class that is a partial abstraction over the DOM. 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.

If ElementRef is injected to a component, the injected instance is a reference to the host element of the current component.

There are other ways to acquire an ElementRef instance like @ViewChild(), @ViewChildren(), @ContentChild(), @ContentChildren(). In this case ElementRef is a reference to the matching element(s) in the template or children.

Renderer and ElementRef are not "either this or that", but instead they have to be used together to get full platform abstraction.

Renderer acts on the DOM and ElementRef is a reference to an element in the DOM the Renderer acts on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...