How to Access the Controller and Viewmodel of an Aurelia 2 Component

In Aurelia 1, you could access the controller of an Aurelia component by accessing au.controller of an element. In Aurelia 2, there is a better way using the CustomElement.for method, which provided an element with a controller that will return it.

const dialogController = CustomElement.for(host.querySelector(".my-component") as HTMLElement);
 const dialogVm = dialogController.viewModel;

You can also access a property on the element if you prefer using: element.$au['au:resource:custom-element'] – but the provided method might save you the hassle of having to type things if you’re working with TypeScript.