bind #element to element 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')));}
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.tsimport { 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.tsexport class AppComponent implements AfterViewInit { // ... @ViewChildren(DivIdDirective) els: QueryList<DivIdDirective>; ngAfterViewInit(): void { console.log(this.els.map(({id, el}) => ({id, el})); }}