Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Get reference to element created in ngFor

Tags:

angular

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.

like image 305
Mathijs Segers Avatar asked Mar 22 '16 06:03

Mathijs Segers


4 Answers

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');
}
like image 163
Günter Zöchbauer Avatar answered Nov 20 '22 03:11

Günter Zöchbauer


<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;
}
like image 43
Nikhil Shah Avatar answered Nov 20 '22 04:11

Nikhil Shah


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>
like image 3
BigBadAlien Avatar answered Nov 20 '22 03:11

BigBadAlien


<div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>

itemClick(dom){
  dom.style.color='red';
  // ...
}
like image 1
gonnavis Avatar answered Nov 20 '22 03:11

gonnavis