I am using *ngFor to create a bunch of divs. I would like to get my hands on one of them an get its width.
.html
<div #elReference *ngFor="let el of elements> HEHE </div>
.ts
@ViewChild("elReference") elReference: ElementRef;
Apparently, you cannot use ViewChild with *ngFor, because elReference
remains undefined.
How do you get element reference created with *ngFor?
There is a more complicated, but more correct way with a directive.
<!-- app.component.html -->
<div *ngFor="let el of elements" [id]="el.id"> HEHE </div>
// div-id.directive.ts
import { Directive, Input, ElementRef } from '@angular/core';
@Directive({
selector: 'div[id]',
})
export class DivIdDirective {
@Input() id: number;
constructor(ref: ElementRef<HTMLDivElement>) {
this.el = ref.nativeElement;
}
el: HTMLDivElement;
}
// app.component.ts
export class AppComponent implements AfterViewInit {
// ...
@ViewChildren(DivIdDirective) els: QueryList<DivIdDirective>;
ngAfterViewInit(): void {
console.log(this.els.map(({id, el}) => ({id, el}));
}
}
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