Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic template reference variable inside ngFor (Angular 9)

People also ask

How do I create a dynamic template reference variable?

To declare dynamic template reference variable inside ngFor with Angular, we can declare one variable. to define the popupContent in the *ngFor loop. export class Component implements OnInit, AfterViewInit { //... @ViewChildren("popupContent") components: QueryList<CustomComponent>; //... }

How do I get the template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

What template reference variable contains?

A template reference variable is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, TemplateRef, or a web component.

What is template reference variable in Angular?

Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component. Template Reference Variable can refer to the following – DOM element. Directives.


Template reference variables are scoped to the template they are defined in. A structural directive creates a nested template and, therefore, introduces a separate scope.

So you can just use one variable for your template reference

<div *ngFor="let member of members">
  <ng-template #popupContent>Hello, <b>{{member.name}}</b>!</ng-template>
  <button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
      I've got markup and bindings in my popover!
  </button>
</div>

and it should work because it has already declared inside <ng-template ngFor

Plunker Example

For more details see also:

  • angular - conditional duplicate templateref in ng-content with selector

This is the best solution I've found: https://stackoverflow.com/a/40165639/3870815

In that answer they use:

@ViewChildren('popContent') components:QueryList<CustomComponent>;

To build a list of those dynamically generated components. Highly recommend you check it out!


Another way to allow this is to create a component that wraps the button and the ng-template

<div *ngFor="let member of members">
    <popover-button [member]="member"></pop-over-button>
</div>

And have the following in the popover-button component

<ng-template #popContent>Hello, <b>{{member.name}}</b>!</ng-template>
    <button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
    I've got markup and bindings in my popover!
</button>