0

I have a ngtemplate which is neccessary for a modal I am creating a name-button(for modal) pair in each paragraph tag and want to create dynamic content for the modal


<ng-container *ngFor="let student of students">
<p>{{student.name}} <button (click)="modalService.show(modalContent)"> </p>
    <ng-template #content>
        .... for listing all details under student like student.roll, student.gender
    </ng-template>
</ng-container>

but since I loop around with the same #content, it recognized for the first time and wont continue to create the template for the id, understandable one.

@ViewChild('content',{static: false}) modalContent: TemplateRef<any>;

so the ngtemplate content is mapped to the above modalContent modelService is a custom service which takes in a TemplateRef.

Ideally I want help in making multiple ngtemplate and mapping with the modalContent

I need a way to access these elements by setting a name tag to i, may be like a dictionary with the string:template

Srinivas Jayaram
  • 315
  • 5
  • 17
  • Possible duplicate of [Access multiple viewchildren using @viewchild](https://stackoverflow.com/questions/40165294/access-multiple-viewchildren-using-viewchild) – Vishal Biswas Oct 27 '19 at 03:44

1 Answers1

0

First step is custom directive

# create a directive here
@Directive({
  selector: 'ng-template[modal-template]'
})
export class ModalDirective {
  @Input('modal-template') name: string;

  constructor(public template: TemplateRef<any>) {}
}

Have the template like,

<ng-template modal-template="{{student.name}}"></ng-template>

and in the main component ts

@ViewChildren(ModalDirective) cellTemplates: QueryList<ModalDirective>;

cellTemplatesMap: any;

...

ngAfterContentInit() {
  this.cellTemplatesMap = this.cellTemplates.reduce((acc, cur) => {
    acc[cur.name] = cur.template;
    return acc;
  }, {});
}