I am sorry if my question was silly, i am having 30+ static ng-container with some unique static #hashtagID but i want to create them dynamically with help of ngFor
public lists = ['food', 'book', ........, 'cook']
expecting output :
<ng-container #food></ng-container>
<ng-container #book></ng-container>
..
..
<ng-container #cook></ng-container>
So i tried almost all ways but no luck,
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">
i am using this #hashTagID as viewContainerRef in .ts file.
@ViewChild('food', {read: ViewContainerRef }) private food: ViewContainerRef;
Please someone help me to resolve this issue.
Possible solution could be creating a directive that will take hash as input and also have reference to ViewContainerRef
:
@Directive({
selector: '[hash]',
})
export class HashDirective {
@Input() hash: string;
constructor(public vcRef: ViewContainerRef) {}
}
Now you can write template as:
<ng-container *ngFor="let item of lists" [hash]="item"></ng-container>
And finally you will be able to get reference to desired ViewContainerRef
through 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With