Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign Hash ID ref id for dynamic element in angular 4, 5

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.

like image 854
Munna Babu Avatar asked Mar 10 '18 18:03

Munna Babu


1 Answers

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

like image 127
yurzui Avatar answered Nov 11 '22 00:11

yurzui