Frigo
Frigo

Reputation: 314

Use of :host selector vs container div

The way I see it, it could be used as a replacement for <div> containers for styling a component. Example:

Using container

@Component({
    template: `
        <div class="container">
            <h1>Some Title</h1>
            <p>Some Content</h1>
        </div>
    `,
    styles: [`
        .container {
            border: 1px solid black;
            display: flex;
        }
    `],
})

Using :host

@Component({
    template: `
      <h1>Some Title</h1>
      <p>Some Content</h1>
    `,
    styles: [`
        :host {
            border: 1px solid black;
            display: flex;
        }
    `],
})

If I understand correctly, these two solve the exact same problem. And it's nice to have one less element and class to worry about in pretty much every single component.

Questions: Is this what :host is intended for? If not, what is the point of it, and what are the best practices for giving style to your component aside from adding containers everywhere?

Upvotes: 8

Views: 3634

Answers (3)

n00dl3
n00dl3

Reputation: 21564

They don't solve the same problem. :host is for styling the host and the .container is for styling any div that has the container class inside your component.

The .container div will not be available for styling outside of your component due to encapsulation while the host element can be styled.

Note that the initial value of the display property is inline, so by default your component will be displayed as an inline element. Maybe you don't want that, especially if you have a block element inside of it which might seem counter-intuitive (even if it's allowed).

Upvotes: 3

Adrian Moisa
Adrian Moisa

Reputation: 4353

I will also add the following observations to the current answers:

class .container

  • If you use class .container than you have to always keep them in sync in case you desire to rename your components. In large apps this tends to happen often in the early stages of development.
  • Also this leaves you open for name collisions especially if you don't have good CSS hygiene habits.
  • It can be mistakenly deleted at run-time by overwriting the element class property. Use element.classList.add(); .remove()

:host

  • spares you the need of a lot of typing (sometimes component names can get long)
  • It is there no matter what classes you add to the element. I believe it must also have precedence over the .container class.
  • (Angular only) Angular emulates same behavior, but if you disable component encapsulation all :host selectors become useless which can lead to the use of .container class.

Upvotes: 0

P.S.
P.S.

Reputation: 16384

:host is styling your wrapper element for the current component (for example <app-header> element), and as I know, it's a short and comfortable way to style elements like this.

Upvotes: 0

Related Questions