I wanted to add different classes to the host element based on certain condition. I could add the classes in the accompanying style file. However, they won’t be available to be used on the host element.
Unless I change the encapsulation mode to ViewEncapsulation.None. That removes the encapsulation and make the style declarations global. Which may not be intended behavior.
But we can use Tailwind arbitrary classes. This way angular directly adds those classes to element. While tailwind classes are global for the entire project so everything works.
But
Tailwind arbitrary class does not work with angular host properties
host: {
class: 'overflow-auto grid',
'[class.grid-rows-[auto_min-content_auto] ]': 'isFilterVisible',
'[class.grid-rows-[auto_min-content] ]': '!isFilterVisible',
}
This end up in generating following classes
<my-component class="grid grid-rows-[auto_min-content\" ></my-component>
We are missing the closing bracket of the arbitrary classes. Tailwind won’t recognize it and will not create a CSS declaration bead on that.
Escaping the the extra bracket has no effects either
host: {
class: 'overflow-auto grid',
'[class.grid-rows-[auto_min-content_auto\\] ]': 'isFilterVisible',
'[class.grid-rows-[auto_min-content\\] ]': '!isFilterVisible',
}
Solution
The solution is to use Component class properties that returns appropriate classes in object
@Component({
host: {
class: 'overflow-auto grid',
'[class]': 'gridClasses()',
}
})
export class MyComponent {
gridClasses = computed(() => {
return {
'grid-rows-[auto_min-content_auto]': this.isFilterVisible(),
'grid-rows-[auto_min-content]': !this.isFilterVisible()
}
})
}
