I'm fairly new to Angular, so some of my assumptions will be wrong.
I want to manipulate an element's styling at runtime using Renderer2.setStyle(elementRef, style, value, flags?)
.
For that, I need an element reference.
The Angular docs always warn against going via a browser's native API to manipulate styling or getting an element reference.
For example, the docs for ElementRef.nativeElement
clearly state:
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 can take a look at Renderer2 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.
Now, the elements I want to style are created on the fly via another component I use. I don't know, for example, how many of them I will need to touch, so using an annotation-based approach doesn't seem feasible. (The child component will also be rendered after any annotation-based selector is evaluated, I assume?)
Anyhow, I want to select based on CSS class and a custom property, whose value I can compute at runtime (and which will be different from element to element - nothing a for
loop can't handle, but difficult to express in a text selector?):
myClass[myProp="val_1..n"]
Is there a way to get an element reference using an Angular API, ie without going through nativeElement
, like document.querySelector(...)
or ElementRef.nativeElement.querySelector(...)
?
I'm basically looking for something like RendererX.querySelector(componentRef, 'selector')
- but I take it Renderer2.selectRootElement(...)
is not what I'm looking for...
tldr: how do I go from CSS selector to element reference without going via browser API/DOM methods like document.querySelector(...)
or calling nativeElement
myself? Is there an Angular API abstraction?