12

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?

4

2 回答 2

9

无法有选择地添加模板变量,但您可以有选择地添加标记,然后按此过滤:

<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')));
}
于 2017-10-31T11:21:57.193 回答
4

指令有一种更复杂但更正确的方法。

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

于 2021-04-07T14:26:44.020 回答