I am using *ngFor
to create a bunch of div
s. I would like to get my hands on one of them and 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 no way to add a template variable selectively, but you can add a marker selectively and then filter by that:
<div #elReference [attr.foo]="el.x == 'foo' ? true : null" *ngFor="let el of elements"> HEHE </div>
@ViewChildren("elReference") elReference: QueryList<ElementRef>;
ngAfterViewInit() {
console.log(this.elReference.toArray()
.filter(r => r.nativeElement.hasAttribute('foo')));
}