Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind #element to element created with *ngFor

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?

like image 780
sanjihan Avatar asked Oct 31 '17 11:10

sanjihan


1 Answers

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}));
  }
}

like image 50
Eugene P. Avatar answered Sep 21 '22 22:09

Eugene P.