Conditionally Add Attribute
Asked Answered
D

1

6

Is it possible to conditionally add an attribute to an element using binding syntax? I am aware of if.bind, but that targets elements. Rather I am interested in targeting a specific attribute on an element.

Example:

<a href.bind="model.link">${model.text}</a>

If model.link is falsy, then I don't want the href at all--just treat the <a /> as a container element.

I realize I could create two <a /> tags--one with the attribute and one without--and use an if.bind on both, but that seem clunky and un-aurelia like.

Discernible answered 15/9, 2017 at 3:57 Comment(1)
That still outputs the href itself though. The corresponding URL is blank, but it's still treated like a hyperlink. I don't want to style the <a /> as a hyperlink if there is no URL.Discernible
E
7

I don't think it's supported in Aurelia currently (issue 1, issue 2)

This,

<a href.bind="addLink ? link : ''">Link</a>. 

will produce

<a href>Link</a>

if addLink is false.

It won't remove the attribute entirely. If you are using a library which will check the existence of an attribute to manipulate the element, then this won't work. Another option would be to create a custom attribute like this. But that seems like an overhead.

Extremadura answered 15/9, 2017 at 6:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.