Access a DOM element in Aurelia

前提是你 提交于 2019-12-01 02:08:36
Matthew James Davis

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

EisenbergEffect

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

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>
    }
}
LordZardeck

Just as another point I came across when trying to use this for myself, the ref variable isn't available during construction, and this isn't clear in the documentation. You can begin to reference the element as mentioned above (http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-basics/5) anytime during or after the attached method is called.

Typescript version

@transient()
@autoinject
export class ViewModel { 
    myForm: any;
    canDeactivate() {
        var form = this.myForm;
        // do stuffs
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!