Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Insert template after element

Tags:

angular

I have the following html (simplified for illustration).

//removed irrelevant HTML
<tbody>
  <tr *ngFor="let el of elements; let i = index" >
      <td>
         <button (click)="showTemplate(i, $event)">Click me {{i}}</button>
      </td>
  </tr>
</tbody>

<template #myTemplate>
   <tr>
      <td>You have clicked a button</td>
   </tr>
</template>

What I would like to achieve is that when a button is clicked in a specific tr, the template should be inserted after that specific tr.

What I thought I could do is to get the templateRef using ViewChild and then get its node and use something like:

@ViewChild('myTemplate', {read: TemplateRef}) myTemplate;

showTemplate(i, event) { 
   // i would get selectedTR from the event
   selectedTR.insertAdjacentElement('afterend', this.myTemplate.elementRef.nativeElement)`
}

but all I get from this.myTemplate.elementRef.nativeElement when the function is run is

Is the method I am following the correct one? If it is, then what could possibly be wrong with my setup? If not, is there a more Angular oriented solution?

Please note I am using Angular 2.

like image 747
AngularDebutant Avatar asked Apr 13 '26 15:04

AngularDebutant


1 Answers

While it doesn't answer your question about inserting a template, here is how I would solve your issue:

<tbody>
    <ng-container *ngFor="let el of elements; let i = index">
        <tr>
            <td>
               <button (click)="showTemplate(el)">Click me {{i}}</button>
            </td>
        </tr>
        <tr *ngIf="el.showTemplate">
            <td>You have clicked a button</td>
        </tr>
    </ng-container>
</tbody>

TS:

showTemplate(el: any): void {
    el.showTemplate = true;
}

This is effectively the same solution as your template binding though it is simpler and the template HTML (the second TR in this case) is bound to the model properly.

like image 132
Simon K Avatar answered Apr 16 '26 06:04

Simon K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!