My question is that can I use viewchildren to access a specific element with some dynamic id inside *ngFor? using viewchildren it returns an array of all the elements with that reference variable. If I give some id to every element which is dynamically updated, can I access the element using this id ?
Example HTML :
<div #divs *ngFor="let item of [1,2]" [id]="'div-' + item">
Div {{item}}
</div>
<button (click)="getDivs()">Get divs</button>`
Example TS :
@ViewChildren("divs") divs: QueryList<ElementRef>;
I know we can loop through the querylist but I want to know if we can access by some identifier like id.
If I want to access id = "div-2" and change its color to red, or do something else, how can I do that?
Any help is much appreciated. Thanks in advance!
If you want to handle a different style for an individual
divby usingViewChildren, you could do it by listening to a click event on eachdivand then find that div clicked with itsidfrom the array like the following:component.ts
template
Or handle the styles with a
cssclass within the template HTML like so:template
css
Demo