Search code examples
angularangular2-template

Binding: Appending to href


In my Angular 2 test app, I am trying to append an id the following as part of my HTML template:

<a href="https://www.domainname.com/?q="+{{text.id}}>URL</a>

Not this fails with an error:

(Error: Failed to execute 'setAttribute' on 'Element')

and I am not sure how to append {{text.id}} to this URL.

Do I need to do this in my component, or can it be done somehow inside the HTML template?

BTW, as one would expect, this works just fine (but that's not what I want to do, I need to append text.id to url):

<a href="https://www.domainname.com/?q=">{{text.id}}</a>

Any suggestions?


Solution

  • Use either:

    <a href="https://www.domainname.com/?q={{text.id}}">URL</a>
    

    or (from the official docs):

    <a [href]="'https://www.domainname.com/?q=' + text.id">URL</a>
    



    Regarding the question, it's important to notice: The error message is misleading.

    When you use {{ expression }}, angular will evaluate the expression and place its value right where the {{}} is. So you don't need to + the result of {{}} to the string as you do. In other words:

    <a href="something="+{{ expression }}> WRONG </a>
    
    <a href="something={{ expression }}"> RIGHT </a>
    <a [href]="'something=' + expression"> RIGHT </a>