26

I'm trying to set up a Bootstrap tab strip with Angular 2. I have the tabs rendering in an ngFor but I'm getting template errors when I try to put the # infront of the href expression. So this template compiles but isn't what I want:

<ul class="nav nav-tabs" role="tablist">
  <li *ngFor="let aType of resourceTypes; let i = index"
      [ngClass]="{'active': i == 0}"
      role="presentation">
    <a [attr.href]="aType.Name"
       [attr.aria-controls]="aType.Name"
       role="tab"
       data-toggle="tab">
      {{aType.Name}}
    </a>
  </li>
</ul>

What I want to do is [attr.href]="#aType.Name" but that blows up. What is the correct syntax to prepend the # in front of the expression in the attribute directive?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
cobolstinks
  • 6,801
  • 16
  • 68
  • 97

3 Answers3

51

There is no need to prefix with #

In this code

<ul class="nav nav-tabs" role="tablist">
  <li *ngFor="let aType of resourceTypes; let i = index"
      [ngClass]="{'active': i == 0}"
      role="presentation">
    <a [attr.href]="aType.Name"
       [attr.aria-controls]="aType.Name"
       role="tab"
       data-toggle="tab">
      {{aType.Name}}
    </a>
  </li>

aType already refers to the *ngFor variable.

If you want to prefix a literal # you can use

[attr.href]="'#' + aType.Name" 

There is also no need for attr. if the element actually has the property href which is the case with <a>.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
12

Well you can bind it with string interpolation:

href = "#{{aType.Name}}" 

(Note that the attribute used here is href, not [attr.href].)

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
1

Why don't you use routerLink instead of href? I think, this will work

<a routerLink="#{{ aType.Name }}">Name<a>
Gh111
  • 1,362
  • 18
  • 19