简体   繁体   中英

Accessing a parent component's ViewModel property from the child's ViewModel in Aurelia

I have two components:

<parent-component type="permanent">
    <div child-component></div>
</parent-component>
class ParentComponentCustomElement {
    @bindable public type: string = "permanent";
}

class ChildComponentCustomAttribute {
    public attached() {
        // how to get the instance of ParentComponentCustomElement here?
    }
}

I need to access the type property of the parent to add some classes to the child-component conditionally.

I could probably traverse the parent tree through DOM and look for this specific component, but I don't think that's the correct way to do this.

Have you tried to implement the bind() method for the custom attribute? Try something like this:

 bind(bindingContext, overrideContext) { console.log(overrideContext.parentOverrideContext.bindingContext.somePropertyFromParentViewModel); } 

Source: http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/creating-components/3

Turns out I can just @inject the parent ViewModel into the child component like this:

import {inject, Parent} from 'aurelia-framework';

class ParentComponentCustomElement {
    public type: string = "permanent";
}

@inject(Parent.of(ParentComponentCustomElement))
class ChildComponentCustomAttribute {

    public constructor(private parent: ParentComponentCustomElement) {}

    public attached() {
        console.log(this.parent.type); // permanent
    }
}

Note that this is also convenient as it traverses the parent tree until it finds the component you're actually looking for, so the child can be wrapped in a completely different component and this will still work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM