Getting a specific element in ngFor using Viewchildren

33 views Asked by At

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!

1

There are 1 answers

0
Andres2142 On

If you want to handle a different style for an individual div by using ViewChildren, you could do it by listening to a click event on each div and then find that div clicked with its id from the array like the following:

component.ts

@Component({...})
export class MyComponent {
  ids = [1, 2]
  selected!: string | undefined;
  @ViewChildren('divs') divs!: QueryList<ElementRef>;

  setColor(): void {   
    if (selected) {
     const found = this.divs.find(e => e.nativeElement.id === this.selected)
     console.log('element found: ', found)

     // apply a style to it
     if (found) {
       found.style.backgroundColor = 'blue'
     }
    }    
  }
}

template

<div 
 #divs 
 *ngFor="let item of ids" 
 [id]="'div-' + item" 
 (click)="selected = 'div-' + item"> // click on a div will set its id to "selected"
     <h1>Div  {{item}}</h1>
</div>
  
<button (click)="setColor()">Get divs</button>

Or handle the styles with a css class within the template HTML like so:

template

<div 
 #divs 
 *ngFor="let item of ids" 
 [id]="'div-' + item" 
 [class.colorBlue]="{ selected === 'div-' + item }"
 (click)="selected = 'div-' + item">
     <h1>Div  {{item}}</h1>
</div>

css

.colorBlue {
  background-color: blue;
}

Demo