Search code examples
aurelia

bind to css visibility


Using Aurelia's css bind you have to use this syntax

<div css.bind="{visibility: someField ? 'visible':'hidden'}">

is there a more succinct way to do this?

Please note, using show.bind is not what i'm after as this is equivalent to display:none and I actually want visibility:hidden (so the element takes up its space but is not visible)

Something like this would be ideal

<div visibility.bind="someField">

Solution

  • A little simpler syntax would be:

    <div css=“visibility: ${someField ? 'visible':'hidden'}”>
    

    To make this more succinct, you can easily create a custom attribute:

    import {inject} from 'aurelia-framework';
    
    @inject(Element)
    export class VisibilityCustomAttribute {
        constructor(element) {
            this.element = element;
        }
    
        valueChanged(newValue) {
            this.element.style.visibility = newValue ? 'visible' : 'hidden';
        }
    }
    

    And use it like this:

    <template>
      <require from='./visibility-custom-attribute'></require>
      <div visibility.bind="someField">
    </template>
    

    See this GistRun for an example.