Usage: host selector versus container div

As I can see, it can be used as a replacement for <div> containers to style a component. Example:

Container use

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

Usage : 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 same problem. And it's nice to have one less element and class that you need to worry about in almost every single component.

Questions: what is :host ? If not, what is its essence and what are the best methods for providing style to your component besides adding containers all over the world?

+5
source share
3 answers

They do not solve the same problem. :host is for styling a host, and .container is for styling any div that has a container class inside your component.

The .container separator .container not accessible 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. You may not want this, especially if you have a block element inside it that may seem to contradict intuition (even if it is allowed).

+3
source

:host stylizes your wrapper element for the current component (for example, <app-header> ), and, as I know, this is a short and convenient way to style such elements.

0
source

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

class .container

  • If you use the .container class, you should always synchronize them if you want to rename your components. In large applications, this often happens in the early stages of development.
  • It also leaves you open to name collisions, especially if you don't have good CSS hygiene skills.
  • It can be mistakenly deleted at runtime by overwriting an element's class property. Use element.classList.add(); .remove() element.classList.add(); .remove()

: master

  • eliminates the need to type a lot (sometimes component names can drag out)
  • This is regardless of what classes you add to the element. I believe that it should also take precedence over the .container class.
  • (Angular only) Angular emulates the same behavior, but if you disable component encapsulation, all :host selectors become useless, which can lead to the use of the .container class.
0
source

Source: https://habr.com/ru/post/1272161/


All Articles