Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a DOM element in Aurelia

How would you go about accessing a DOM element in Aurelia? This is a broad and general question, but I have a feeling there are one or two preferred ways to do this. I have two current cases in Aurelia now:

In the template I have a form. I want to access the form element in the view-model, on VM canDeactivate(), to interrupt a user navigating away from a half filled out form. So the scope in which I'm trying to access the element can be considered local.

In another view-model I want to hide navigation on VM activate(). Navigation resides in another view-model/template pair so the scope may be considered global.

like image 653
WeeHorse Avatar asked Apr 25 '15 08:04

WeeHorse


People also ask

How do I access DOM elements?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

How do I find the HTML element of a DOM?

The easiest way to find an HTML element in the DOM, is by using the element id.

What is DOM element?

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.


3 Answers

As Rob suggested, use ref. For your example:

view

<form ref="myForm"></form>

viewModel

class ViewModel { 

    canDeactivate() {
        var form = this.myForm;
        // do stuffs
    }
}

For more information on the ref attribute, see here: http://aurelia.io/docs/binding/basics#function-references

like image 144
Matthew James Davis Avatar answered Oct 08 '22 22:10

Matthew James Davis


Use binding system's ref capability. See the docs http://aurelia.io/docs/binding/basics#referencing-elements

like image 45
EisenbergEffect Avatar answered Oct 08 '22 21:10

EisenbergEffect


Another option; if your view-model is exposed as a @customElement, its DOM element can be injected in the constructor:

@customElement
@inject(Element)
export class MyCustomElement {
    constrctor(element) {
        logger.info(element) // ==> <my-custom-element></my-custom-element>
    }
}
like image 33
Eliran Malka Avatar answered Oct 08 '22 22:10

Eliran Malka