Dynamic href and id in template in Angular 6

Issue

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.

Solution

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>

Answered By – shadowman_93

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published