3

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
  • it is not necessary for ngClass to use in a div tag, you can also use ngClass in other tags, such as in your case h1 or p. you can add conditional class in these tags too. in this way you don't need any extra div to wrap your component. Commented May 22, 2020 at 23:49

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.