Applying classes to custom elements in both its view and its parent's view

Sometimes I want to attach classes directly to the top level of a custom element that will always be present on the custom element, regardless of where it’s being used, while also wanting to be able to add additional classes to it depending on the context of where it’s being used.

Therefore, how can I apply classes to a custom element in both the custom element’s view and in the parent/consuming view?

For example, if I have a custom element:

custom-element.html

<template class="custom-element-class">
  ...
</template>

and I then want to add a class to it in the parent view, where I’m consuming it:

parent-element.html

<custom-element class="context-specific-class"></custom-element>

then context-specific-class will always overwrite custom-element-class.

Is there a way to get around this without having to nest everything in the custom element in a redundant div, like this?

<template>
  <div class="custom-element-class">
    ...
  </div>
</template>
1 Like

You don’t mention it, but have you looked at style and css binds versus class? I believe they are additive to the class.

https://aurelia.io/docs/binding/class-and-style#class

1 Like

I have, this is more a question about whether it’s possible to combine classes additively. I realize there are messier ways to get around my issue so that styles can be applied by both the element itself as well as its consumer, but I’m looking for a more elegant solution (if it exists).

1 Like

I am not sure if it has to do with any recent updates, since your post is about 3 months old now, but I just tried the code below:

app.html:

<template>
  <require from="custom-element.html"></require>
  <custom-element class="context-specific-class"></custom-element>
</template>

custom-element.html:

<template class="custom-element-class">
  This is a custom element
</template>

This seems to work just fine. Both custom-element-class and context-specific-class are assigned to the <custom-element> element when I inspect it in the browser.

Am I perhaps misinterpreting your issue at hand? (I don’t think so, since I remember a similar issue when I tried something like this a while ago, but I fail to reproduce it now. So I do suspect that something got updated in Aurelia lately.)

1 Like