In Angular we create components, which render a template. Much like Web Components, Angular declares which components to render by using the custom HTML element.
Let’s assume you have a PizzaListComponent
which has a pizza-list
selector:
@Component({
selector: 'pizza-list',
template: `<div>🍕</div>`,
styles: [``]
})
export class PizzaListComponent {}
To use the component we’ll declare it in our HTML as follows:
@Component({
selector: 'pizza-list',
template: `
<h1>Pizzas</h1>
<pizza-list></pizza-list>
`,
})
export class AppComponent {}
The problem lies in when we want to style our components, for example using flexbox.
Flexbox introduces the issue of having that “extra element” in the rendered DOM, which can break the layout.
It might be tempting to start targeting the element name and applying styles like this:
@Component({
selector: 'pizza-list',
template: `
<h1>Pizzas</h1>
<pizza-list></pizza-list>
`,
styles: [`
/* target the element directly */
pizza-list {
display: flex;
}
`]
})
export class AppComponent {}
But this creates a tightly-coupled styling solution that is not reusable and doesn’t allow the child component to be moved around without breaking styles elsewhere.
So what can we do? Style the host element itself to apply styles with Angular.
To do this, we can use the :host
target selector, which will apply styles to the actual containing element <pizza-list>
and not the first child element.
@Component({
selector: 'pizza-list',
template: `<div>🍕</div>`,
styles: [`
:host {
display: flex;
}
`]
})
export class PizzaListComponent {}
And that’s it. Use the :host
selector when you need to style a component’s outer element in Angular. By doing so we create a far more reusable component that also encapsulates its own styles - for maximum reuse and predictability.
🚀 Want to learn even more awesome Angular practices?
Check out my new Angular Courses if you’re serious about taking your skills to the top! There’s so much about Standalone Components and all the new best practices in the course.
Thanks for reading, happy styling!