我很抱歉,如果我的问题很愚蠢,我有30多个静态ng-container和一些独特的静态#hashtagID,但我想借助ngFor动态创建它们
public lists = ['food', 'book', ........, 'cook']
期待输出:
<ng-container #food></ng-container>
<ng-container #book></ng-container>
..
..
<ng-container #cook></ng-container>
所以我几乎尝试了所有方法,但没有运气,
1: <ng-container *ngFor="#id of lists"><ng-container>
2: <ng-container *ngFor="let id of lists" #{{id}}><ng-container>
3: <ng-container *ngFor="let id of lists" #+"id"><ng-container>
4: <ng-container *ngFor="let id of lists" #{id}><ng-container>
5. <div *ngFor="let id of lists" #id></div>
6: <div *ngFor="let id of lists" [id]="id">
我在.ts文件中使用#hashTagID作为viewContainerRef。
@ViewChild(&#39; food&#39;,{read:ViewContainerRef})私人食物:ViewContainerRef;
请有人帮我解决此问题。
答案 0 :(得分:2)
可能的解决办法可能是创建一个将哈希作为输入的指令,并且还引用@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'));
}
:
sed
<强> Example 强>