Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
Angular2 Get reference to element created in ngFor

How would I go for referencing an Element in the dom which was created in a ngFor loop.

e.g. I have a list of elements which I iterate over:

var cookies: Cookie[] = [...];

<div *ngFor="#cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>


<div *ngFor="#cookie of cookies" id="cookie-tab-content-{{cookie.id}}" ">Cookie Details</div>

How would I reference these divs, so I could add a css class like "is-active". Or is my approach just wrong.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

If you want to add/remove a class use binding

<div *ngFor="let cookie of cookies" [class.isActive]="someExpression" ....>

or

<div *ngFor="let cookie of cookies" [ngStyle]="{'isActive': someExpression}" ....>

Concrete example:

activeCookie:string = 'b';
cookies:string[] = ['a', 'b', 'c'];
<div *ngFor="letcookie of cookies" [class.isActive]="cookie == activeCookie" ....>

If you really want to get a reference you can use

<div #someName *ngFor="let cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>

@ViewChildren('someName') someDivs;

ngAfterViewInit() { // or some event handler
  someDivs.toArray()[0].nativeElement.classList.add('isActive');
}
over 4 years ago · Santiago Trujillo Report

0

<style>
      .active{
          background:blue;
      }
</style>



<div [ngClass]="{active:(i==selectedIndex)}" 
     *ngFor="#cookie of cookies;#i=index"        
      id="cookie-tab-button-{{cookie.id}}"  
      (click)="showcookie(cookie,i);">Cookie tab
</div>



showcookie(val, i){
        console.log(val + i);
        this.selectedIndex=i;
}
over 4 years ago · Santiago Trujillo Report

0

You can use ng-container which not be rendered:

<ng-container *ngFor="let cookie of cookies">
  <div id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>
</ng-container>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!