I have some Angular component to which I want to unconditionally assign a class. This can be done using the host
property on the @Component
decorator:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `<!-- template -->`,
host: {
'class': 'my-unconditional-class'
}
})
export class MyComponent {}
However, our linting rules recommend we don't:
Use @HostBinding or @HostListener rather than the
host
metadata property (https://angular.io/styleguide#style-06-03) eslint(@angular-eslint/no-host-metadata-property)
I'm wondering how this is best done then. It seems like the solution would be:
import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `<!-- template -->`,
})
export class MyComponent {
@HostBinding('class.my-unconditional-class')
protected readonly hostClass = true;
}
But that honestly seems like a lot of extra code with no obvious benefit. You also have to name the field something "meaningful". This especially becomes annoying when you start having multiple classes to bind.
Though not improving too much on the extra number of characters for a single class, it seems that for multiple classes on the host, it is shorter to just bind a string to class
:
@HostBinding("class")
protected readonly classes = "my-many unconditional-classes for-the-host";
This also allows for a more generic field name like classes
, hostClasses
or cssClasses
.