Sub topic 1
Declaring Styles on an Angular Component
Prerequisites
Assume you know basic HTML, CSS selectors, specificity, standalone components, and Angular property binding.
Angular lets a component declare CSS beside its template. Use styles for inline CSS or styleUrl for an external stylesheet:
import { Component } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label"><ng-content /></span>`,
styles: `
:host {
display: inline-block;
}
.label {
padding: 2px 8px;
border-radius: 4px;
background: #e0e7ff;
}
`,
})
export class BadgeComponent {}For a separate file, replace styles with styleUrl: './badge.component.css'. Angular includes the stylesheet when it builds the component.
How Emulated encapsulation scopes your CSS
ViewEncapsulation.Emulated is the default. Angular rewrites component selectors and adds generated attributes to the component host and its template elements. As a result, .label normally affects only elements rendered by BadgeComponent.
A selector in one component does not normally style a child component's internal elements. This prevents unrelated components from changing each other accidentally.
Styling the host element with `:host`
The host is the custom element itself, such as <app-badge>. Use :host to style that element:
:host {
display: inline-block;
margin: 4px;
}
:host(.large) {
font-size: 1.25rem;
}:host is useful because ordinary selectors target descendants, not the component's host. Use host classes when the component's state should change its outer appearance.
Conditional styling with class and style bindings
Class bindings add or remove a class. Style bindings set a specific CSS property:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-progress',
template: `
<div class="bar"
[class.done]="percent() === 100"
[style.width.%]="percent()"></div>
`,
styles: `
.bar { height: 8px; background: steelblue; }
.bar.done { background: seagreen; }
`,
})
export class ProgressComponent {
percent = signal(40);
}The common error is confusing [class.done] with [class]: the former controls one class, while the latter can replace the element's complete class value.
Exercise
Which selector styles the component host element when it has a large class?
Show answer
:host(.large).