@ViewChildren
,这基本上是几个
@ViewChild
.
This stackblitz
展示了如何使用它,正如您所看到的,它非常容易使用。
import { Component, QueryList, ElementRef, ViewChildren } from '@angular/core';
@Component({
selector: 'my-app',
template: `<hello name="{{ name }}"></hello>
<div
*ngFor="let index of [1, 2, 3, 4, 5]"
(mouseover)="hovered(divs)"
#divs>
This is the div n° {{ index }}
</div>`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChildren('divs') divs: QueryList<ElementRef<HTMLDivElement>>;
name = 'Angular';
hovered(div: HTMLDivElement) {
// Getting from the query list
const corresponding = this.divs.find(_div => _div.nativeElement === div).nativeElement;
// they are the same
console.log(corresponding);
console.log(corresponding === div);
console.log(div);
}
}