25

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
  • 127,031
  • 74
  • 384
  • 431
cobolstinks
  • 6,327
  • 15
  • 59
  • 88

3 Answers3

49

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
  • 127,031
  • 74
  • 384
  • 431
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
  • 8
    Once difference when using `[attr.href]` vs `[href]` is that the former will not bind if the value is null- this came in handy for me, since I wanted the anchor to be disabled if a url property I was binding wasn't set. – spongessuck Jan 14 '17 at 20:34
  • it gives me link like this. "localhost:4200/mywebsite.com". How can I handle this ? – Ahsan Mar 26 '19 at 11:52
  • What's wrong with that? What is the expected value? – Günter Zöchbauer Mar 26 '19 at 11:54
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
  • 127,031
  • 74
  • 384
  • 431
rinukkusu
  • 21,351
  • 4
  • 61
  • 68
1

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

<a routerLink="#{{ aType.Name }}">Name<a>
Gh111
  • 1,197
  • 16
  • 16