How to inject Element in Aurelia 2

In Aurelia 1, I used to do: import { Element, inject } from 'aurelia-framework'; @inject(Element) class MyClass { constructor(element) { this.element = element } }. How do I do that in Aurelia 2 (using ESNext)? I missed that in the docs (at docs.aurelia.io). Thanks!

1 Like

Hi @frmjp! You need to use the @INode decorator. It looks as follows.

import { INode } from '@aurelia/runtime-html';

public constructor(
  @INode private readonly element: HTMLElement
){}

Note that instead of typing it as HTMLElement, you can also type it as INode. However, the HTMLElement type in this case would be more user-freindly.

1 Like

This works for me in AU2

import { inject } from 'aurelia'

@inject(Element)

class MyComponent {
    constructor(element) {
        this.element = element
    }
}
3 Likes

I still don’t know how to get the current HTMLElement for my component.

  • @INode leads to errors: Type 'InterfaceSymbol<INode<Node>>' has no call signatures.
  • @inject seems to be @deprecated
  • and resolve doesn’t work as well:
private readonly _element = resolve(HTMLElement)
AUR0016:class HTMLElement extends globalObject.Element {
    constructor() {
      return HTMLConstructor_helpers_html_constructor(globalObject, interfaceName, new.target);
    }

resolve(HTMLElement) is fixed in [New release] Au v2 beta 19 - #2 by DannyvanHolten

Maybe you can resolve your issues by trying to create a repo, based on this stackblitz Aurelia app - conventions webpack - StackBlitz

1 Like

Hello,
In Aurelia 2, you can achieve the same functionality with slight adjustments to the syntax. Here’s how you can do it using ESNext:

import { ICustomElementViewModel, customElement } from 'aurelia';

@customElement({ name: 'my-element' })
export class MyClass implements ICustomElementViewModel {
  constructor(@INode private readonly element: HTMLElement) {}
}

In this example, INode is used to inject the DOM element, and customElement is used to define the custom element. This should provide the same behavior as your Aurelia 1 code. For more details, you can check the Aurelia 2 documentation.

I hope this will help you.

Respected community member :smiling_face_with_three_hearts:

1 Like

Thanks, but your example seems to be TypeScript instead of ESNext.