1

我有2個自定義控件parent-controlchild-control。我需要孩子代表父母執行功能。要求是孩子應該在家長範圍內使用。創建新的bindingContext供兒童使用查看模型

使用例

...<content-around> <!-- this is 'outerContext' bindingContext --> 
    <parent-control shared.bind="outerContext.something"> 
    <div> 
     <child-control property="nameOfMemberOfShared"></child-control> 
    </div> 
    <div> 
     <span>some text here</span> 
     <child-control property="anotherNameOfMemberOfShared"></child-control> 
    </div> 
    </parent-control> 
</content-around>... 

父 - control.html

<template> 
    <slot></slot> 
</template> 

父 - control.ts(假設所有的進口)

export class ParentControlCustomElement { 
    @bindable shared: any; 

    bind(bindingContext, overrideContext) { 
    //here want to make sure elements rendered inside slot 
    //are able to access 'shared' 
    } 
} 

兒童control.html

<template> 
    <!-- this is for simplicity more advanced stuff needed here --> 
    <h1>${sharedObject[property]}</h1> 
</template> 

兒童control.ts(假設所有進口)

export class ChildControlCustomElement { 
    @bindable property: string; 
    sharedObject: any; 

    bind(bindingContext, overrideContext) { 
    this.sharedObject = bindingContext.shared; 
    // the problem is HERE! 
    // instead of getting a binding context pointing 
    // to parent-control view model I get binding context 
    // pointing to 'outerContext' 
    } 
} 

如何確保從parent-control開始內部組件將獲得指向parent-control的視圖模型的綁定上下文?

回答

3

如果你知道你的孩子控件將始終父控件內使用,你可以聲明的祖先/父依賴性:

@inject(ParentControlCustomElement) 
export class ChildControlCustomElement { 
    constructor(parentControl) { 
    this.parentControl = parentControl; 
    } 
} 

如果你不能肯定你孩子是否會控制在父母內部使用,請使用@inject(Optional.of(ParentControlCustomElement))

+0

有趣的,讓我試試 –

+0

優秀!!這按預期工作!非常感謝。 –