Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Frigo Avatar asked Oct 17 '22 05:10

Frigo


1 Answers

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).

like image 114
n00dl3 Avatar answered Oct 20 '22 22:10

n00dl3