Aurelia After-Render

One problem I’ve run into a few times is needing to ensure an element is on the page before rendering it. This occurs with 3rd party libraries like Chart.js and with jQuery manipulations when combined with if.bind. One option is to use the attached() lifecycle method, however if the necessary data is fetched during created() is it often not ready by attached(), and therefore it is useful to have an ‘event’ that indicates that the said elements are now available to use.

The solution I used is a basic Custom Attribute. A custom attribute runs its own behaviour lifecycle. Because the attribute is on the element we are waiting for, when the attached() method fires we know the element is attached to the DOM, so we can call the function which is waiting for the element.

The full code for the attribute is below. The attribute will pass a reference to the element to the registered function.

import { bindable, autoinject, customAttribute } from 'aurelia-framework';

@autoinject
@customAttribute('after-render')
export class AfterRenderCustomAttribute {
    private value;

    constructor(private element: Element) { }

    attached() {
        this.value({ele: this.element});
    }
}

To use the attribute, ensure it is included in the template either via a <require> tag or by setting it globally using config.globalResources(). Because the target of the attribute is a method we use .call rather than .bind.

<canvas id="my-chart" after-render.call="drawChart(ele)"></canvas>