5

I'm doing a web application in Angular 6 and I added a tab pane in template. I would like to generate the href and the id dynamically.

<div class="nav-tabs-custom">
  <ul class="nav nav-tabs">

    <li class="active"><a href="#tab_1" data-toggle="tab" aria-expanded="true">Session 1</a></li>

    <ng-container *ngFor="let session of data?.sessions; index as i">
      <li class="" *ngIf="i > 0">
      <a href="#tab_{{i}}" data-toggle="tab" aria-expanded="false">Session {{i + 1}}</a>
      </li>
    </ng-container>

  </ul>
  <div class="tab-content">
    <div class="tab-pane active" id="tab_1">

      Working good.

    </div>
    <!-- /.tab-pane -->

    <ng-container *ngFor="let session of data?.sessions; index as i">
      <div class="tab-pane" id="tab_{{i}}" *ngIf="i > 0">

        Not working.

      </div>
      <!-- /.tab-pane -->
    </ng-container>

  </div>
  <!-- /.tab-content -->
</div>

If my array of Objects contains, for example, 3 Objects, should appear 3 tabs and I should be able to click on them to see the content.

I have tried:

[href]="'#tab_' + i"
[id]="'tab_' + i"

My goal is to generate the href and the id depending on how many Objects I have in my array to be able to click on each tab and see its content.

RRGT19
  • 1,437
  • 3
  • 28
  • 54
  • Possible duplicate of [Dynamically assign element id inside ngFor](https://stackoverflow.com/questions/49589713/dynamically-assign-element-id-inside-ngfor) and Set href in attribute directive in Angular (https://stackoverflow.com/questions/37948504/set-href-in-attribute-directive-in-angular) – Barkha Feb 28 '19 at 13:53

2 Answers2

25

You can easily use this syntax, the following will work as expected:

<a href="{{'#tab_' + your expression here}}"></a>

You can also bind using the attr prefix like this:

<a [attr.href]="'#tab_' + your expression here"></a>
rcanpahali
  • 2,565
  • 2
  • 21
  • 37
  • Can you please produce your issue on stackblitz? Or just write down your variable which is {{'#tab_' + your expression here}} somewhere on page, so you can see that what you are actually generating... – rcanpahali Feb 28 '19 at 14:50
  • It's working right now. I had a logic issue with my `ngIf` inside the `ngFor`. I have used `href="{{'#tab_' + i}}"` and `id="{{'tab_' + i}}`. – RRGT19 Feb 28 '19 at 16:27
3

Below solution work for me:

<a href="{{'mailto:' + data.emailId }}"> Send Mail </a>
<a href="{{'tel:' + data.phoneNumber }}"> +911234567890 </a>
<a href="{{'/' + data.redirectURL }}"> Open Google </a>
Abdullah
  • 2,393
  • 1
  • 16
  • 29