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.
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');
}
<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;
}
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>
<div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>
itemClick(dom){
dom.style.color='red';
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With