SoFunction
Updated on 2025-04-12

Angular5 method to add style class to the label of the component itself

There are two ways to add styles to the labels of the component itself in Angular 5:

Method 1: Use @Component's host property

@Component({
 selector : 'myComponent',
 host : {
  '[]' : "'red'", 
  '[-color]' : 'backgroundColor'
 }
})
class MyComponent {
 backgroundColor: string;
 constructor() {
   = 'blue';
 }
}

Adding attributes in the host configuration is the same as using the binding attributes on the tag.

Set style:

  1. '[]': "'red'": Note that there is a single quote in the double quotes of the red value.
  2. '[-color]':'backgroundColor': Here is a reference to the variable backgroudColor in the component.

The advantage of this approach is that the component's variables can be used on the style.

Set class:

@Component({
 selector : 'myComponent',
 host : {
  '[]' : 'showMyClass'
 }
})
class MyComponent {
 showMyClass = false;
 constructor() {
 }

 toggleMyClass() {
   = !;
 }
}

Method 2: Use:host selector in style

@Component({
 selector : 'myComponent',
 styles : [`
  :host {
   color: red;
   background-color: blue;
  }
 `]
})
class MyComponent {}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.