Apply CSS class conditionally to Angular component host

Viewed 1707

I have an angular component with boolean input parameters. Based on whether they are true or false, I want to add a CSS class to the host. I know I can wrap my entire component in a div and use ngClass. But what if I don't want to add an extra div in my template? I just want the host to have those classes conditionally. Is that possible? Say this is my component:

 export class AssetDetailsComponent {
  @Input isSomethingTrue = true;
  @Input isThisAlsoTrue = true;

  constructor() {}
}

And this is what the template looks like:

<h1> Page heading </h2>
<p> Details </p>

Now based on the value of isSomethingTrue and isThisAlsoTrue, I want to apply 2 different CSS classes or styles to the host (to add some margin-top). How do I do that in the component?

1 Answers

You can combine @HostBinding with an @Input property to apply a class conditionally to the component host, based on the property value. In the code below, classes class1 and class2 are applied to the host element depending on condition1 and condition2 respectively:

@HostBinding("class.class1") @Input() condition1: boolean;
@HostBinding("class.class2") @Input() condition2: boolean;

The CSS styles can be defined as follows:

:host.class1 {
  margin-top: 20px;
}
:host.class2 {
  margin-left: 10px;
}

See this stackblitz for a demo.


An alternative syntax is to set the host class bindings in the component metadata:

@Component({
  ...
  host: {
    "[class.class1]": "condition1",
    "[class.class2]": "condition2"
  }
})
export class ChildComponent {
  @Input() condition1: boolean;
  @Input() condition2: boolean;
}

See this stackblitz for a demo.

Related