Beese
Beese

Reputation: 525

Usage of ElementRef in Attribute Directive?

I was wondering.. Is it considered bad practice to use ElementRef in an attribute directive? Currently I am positioning some elements based on a Date variable (a timetable), and in the future want to be able to drag and drop the elements, and send the new date and time information to a database (based on the position). I found that I could do this using a Directive. But then I looked at the documentation for ElementRef which states:

USE WITH CAUTION

Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported.

Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.

So my question is would you consider the movement of my elements as "last resort"? If not, how would you alternate the position of an element depending on these kinds of variables?

Upvotes: 2

Views: 967

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657476

Somehow I think they tried to maximise confusion with this documentation.

Using ElementRef is perfectly fine.
What the docs actually refer to, is accessing methods or fields of ElementRef.nativeElement.

Angular goes great lengths to abstract the DOM and allow you to avoid direct DOM access to not have a strong dependency to the browsers DOM.
This allows to run Angular on the server for Server Side Rendering or in WebWorkers to spread the load over multiple CPU cores.

If you want to use SSR or Web Workers, just stay away from direct DOM access as far as possible.

If you don't intend to use SSR or Web Workers, direct DOM access is fine, especially if your are using non-Angular libraries that access the DOM directly anyway.

Upvotes: 1

Related Questions