2

I would like to join a string in an expression in Angular2, though seem unable to do so. (Specifically in the attr.href of the a tag.

For example, assume that I have a url made of '/page/id', and the ID is stored in a variable.

   <a [attr.href]="/page/{{id}}">link</a> 

This will not work, because we can not use {{}} syntax in an expression.

I am not sure how I would go about joining strings here.

4
  • haha too quick both @Gunter and @Thierry for answer. well apart from answer see here explanation of when to use {{}} and [] property binding stackoverflow.com/a/36528964/5043867 Commented Apr 11, 2016 at 8:52
  • You don't need attr in this case. See my updated answer. Commented Apr 11, 2016 at 8:52
  • Yeah they were amazingly fast actually! Commented Apr 11, 2016 at 8:53
  • Hmm No doubt ! @DylanMeeus Commented Apr 11, 2016 at 8:54

2 Answers 2

9

You could try this:

<a [attr.href]="'/page/' + id">link</a>

Since in this case you can't use interpolation (because of [...]). Angular2 will try to evaluate the expression and you can use string value delimited with quotes here.

Sign up to request clarification or add additional context in comments.

1 Comment

This solved the problem, thanks! I need to wait some minutes before I can accept this as the correct answer :)
4

You can't use [...] and {{..}} together either

 <a attr.href="/page/{{id}}">link</a> 

or

 <a [attr.href]="'/page/' + id">link</a> 

There is no need for attr because the href property reflects to the href attribute automatically (Plunker example).

 <a href="/page/{{id}}">link</a> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.