可能的解决方案是创建一个将哈希作为输入并引用
ViewContainerRef
:
@Directive({
selector: '[hash]',
})
export class HashDirective {
@Input() hash: string;
constructor(public vcRef: ViewContainerRef) {}
}
现在,您可以将模板编写为:
<ng-container *ngFor="let item of lists" [hash]="item"></ng-container>
最后,您将能够获得所需的参考
ViewContainerRef
通过
ViewChildren
:
@ViewChildren(HashDirective) private hashes: QueryList<HashDirective>;
lists = ['food', 'book', 'cook'];
getContainerFor(name: string) {
return this.hashes.find(x => x.hash === name).vcRef;
}
ngAfterViewInit() {
console.log(this.getContainerFor('food'));
}
Example