How to Get the Viewmodel of an Aurelia 2 Component

In Aurelia 1, you could access the controller and ViewModel of an element using au.controller and in Aurelia 2, it’s more of the same (except the properties are different). Here is how you get the controller and ViewModel of an element in Aurelia 2.

import { Controller, ICustomElementViewModel } from "aurelia";

// Define an interface for Aurelia element
export interface AuElement extends Element {
  $au: {
    "au:resource:custom-element": Controller;
  };
}

/\*\*
 \* This function receives an element and extracts the Aurelia controller associated with it.
 \* @param {Element} element - The target element 
 \* @returns {Controller|null} - The controller or null if it does not exist
 \*/
export function getElementController(element: Element): Controller | null {
  const auElement = element as AuElement;

  if (!auElement.$au) {
    return null;
  }

  return auElement.$au['au:resource:custom-element'];
}

/\*\*
 \* This function gets the View Model associated with a given element.
 \* @param {Element} element - The target element 
 \* @returns {T|null} - The View Model or null if it does not exist
 \*/
export function getElementViewModel(element: Element): T | null {
  const controller = getElementController(element);

  return controller ? controller.viewModel as T : null;
}