josh_in_dc
josh_in_dc

Reputation: 119

HostBinding not working as expected when applying class

I was reading an article about common bad practices when creating components. One of the things the article mentioned was adding extra tags (like ) to your component template to group everything generated by the component. This is unnecessary because everything generated by your component is already grouped in its selector tags. Makes sense, so I wanted to go about cleaning this up in my code.

So I wanted to use @HostBinding to apply the style class to the component and remove the unneeded tag, but it's not working and I'm not sure what I'm doing wrong. Here's a basic example. The classes that I'm trying to apply are from bootstrap css.

Before:

import {Component, HostBinding} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title = 'app';
}

and the template

<div class="container">
  <div class="col-md-5">
    <h1>Welcome to {{title}}!</h1>
  </div>
  <div class="col-md-5">
    <h2>Here are some links to help you start: </h2>
    <ul>
      <li><h2>x</h2></li>
      <li><h2>y</h2></li>
      <li><h2>z</h2></li>
    </ul>
  </div>
</div>

This works like I want to. The container is centered in the middle of the screen.

I removed the outermost div from the template and then added @HostBinding to the component.

After:

import {Component, HostBinding} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  @HostBinding('class') className = 'container';
  title = 'app';
}

And the updated template

<div class="col-md-5">
  <h1>Welcome to {{title}}!</h1>
</div>

<div class="col-md-5">
  <h2>Here are some links to help you start: </h2>
  <ul>
    <li><h2>x</h2></li>
    <li><h2>y</h2></li>
    <li><h2>z</h2></li>
  </ul>
</div>

When I use my browser's dev tools to inspect the generated page, the class is there (my app-root tag has the class="container" attribute on it), but the style is incorrect. Am I missing or misunderstanding something when it comes to HostBinding?

Upvotes: 0

Views: 3336

Answers (1)

Steve Land
Steve Land

Reputation: 4862

I'm making some assumptions about your app, but I think the issue is that you're probably trying to use it in your root component, meaning that it will be trying to set that class on a parent element that Angular doesnt have any control over.

If you had a child component within your app-root then you could use @HostBinding('class') className = 'container'; in the child component to set a class for the parent (app-root) component.

Upvotes: 1

Related Questions