1

I want to set the binding context for my custom element. something like

<my-custom-element context.bind="someproperty"></my-custom-element>

How can this be achieved? Thanks.

Gena Verdel
  • 588
  • 5
  • 21

2 Answers2

2

If you're trying to access the parent binding context from within a custom element, you can simply use $parent.someproperty in the view to go up a level. If all you need to do is access the parent you can combine this with with.bind="$parent" It's the other way around but it accomplishes the same thing.

Setting the binding context of a custom element in itself doesn't really make sense because that would mean you're changing the ViewModel

Fred Kleuver
  • 7,797
  • 2
  • 27
  • 38
  • That's what I'm trying to do. I want the custom element to be declared in the parent view yet have different binding context which is created dynamically. – Gena Verdel Sep 28 '18 at 09:44
  • 2
    This happens automatically if you use ``. It will inherit the binding context from the parent. If you have a regular custom element then that will always have its own binding context – Fred Kleuver Sep 28 '18 at 11:58
1

if you want to know the binding context within the component/custom element you can access it from the bind component lifecycle method, i.e.:

class MyCustomElement {
  context;
  bind(context, overrideContext) {
    this.context = context;
  }
}

https://aurelia.io/docs/fundamentals/components#the-component-lifecycle for my details

jbockle
  • 633
  • 5
  • 11
  • 1
    Actually that would be `overrideContext.parentOverrideContext.bindingContext` to get the parent binding context, which I believe is what he's trying to do. Under the hood this is also what `$parent` does – Fred Kleuver Sep 28 '18 at 00:38