Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set href in attribute directive in Angular

Tags:

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?

like image 859
cobolstinks Avatar asked Jun 21 '16 15:06

cobolstinks


People also ask

Can I use href in Angular?

AngularJS ng-href DirectiveThe ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.

How would you add a hyperlink in a view in Angular 4?

If you are using routing and want to add a href attribute to a specific route. Use the routerLink directive as it will add the href attribute to <a> tags. Show activity on this post. Show activity on this post.

What is attribute directive in Angular?

The attribute directive changes the appearance or behavior of a DOM element. These directives look like regular HTML attributes in templates. The ngModel directive which is used for two-way is an example of an attribute directive.

What is attribute in Angular?

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.


2 Answers

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>.

like image 95
Günter Zöchbauer Avatar answered Sep 25 '22 13:09

Günter Zöchbauer


Well you can bind it with string interpolation:

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

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

like image 38
rinukkusu Avatar answered Sep 25 '22 13:09

rinukkusu