I found the usage of :host in angular is very confusing.
For example, there is a CSS file a-component.component.css, and its related HTML file is a-component.component.html whose selector is app-a-component.
And in the CSS file there is a statement
h1 {
font-size: 12px;
}
I think this CSS only applies to the <app-a-component> HTML element beased on the following explanation, is that correct?
And if I change the CSS to
:host h1 {
font-size: 12px;
}
(adding :host)
it will still applies to the same <app-a-component> HTML element, because it is the host HTML element of this component, is that correct?
If they are both correct, why would we need :host given it is the same effect with or without it?
Thanks in advance!
In your example :host h1 { ...} there's no difference. Where the :host becomes useful is when you need to use ::ng-deep or you want to style the host element.
e.g.
You have a component <my-component></my-component> and you want to apply styles directly to that element. You can add the styles with the :host selector.
:host {
background: red;
}
This will set the background of the my-component element to red.
For :host ::ng-deep { ... you can disable ViewEncapsulation for that rule but ONLY for descendant components. If you were to just use ::ng-deep without the :host that will become a global style.