Each Angular component carries its own CSS, and Angular keeps it inside the component. This part covers component styles, how encapsulation works, :host, host bindings, CSS custom properties for themes, and enter and leave animations.
Every component so far has borrowed the browser’s default look. Real components carry their own CSS: a badge knows its colours, an alert knows its border. In Angular, that CSS lives with the component, and Angular makes sure it styles that component and nothing else.
This part covers the styles and styleUrl settings, how Angular keeps a component’s CSS inside it, :host for the component’s own tag, the host setting for classes on that tag, CSS custom properties for theming, global styles, and animate.enter / animate.leave. In Part 2 we met [class.x] and [style.x], and in Part 5 we passed inputs to child components. Here we put them together. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
This page has two components. Note is a child with one paragraph. App has its own paragraph, shows a Note, and has a CSS rule for p:
// src/app/note.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-note',
template: `<p>A note from the child</p>`,
})
export class Note {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Note } from './note';
@Component({
selector: 'app-root',
imports: [Note],
template: `
<p>Text in App</p>
<app-note />
`,
styles: `
p {
color: red;
text-transform: uppercase;
}
`,
})
export class App {}
In plain HTML, a p { ... } rule styles every paragraph on the page. Before you read on, guess: which paragraphs turn red and upper case?
The page shows:
TEXT IN APP
A note from the child
Only App’s own paragraph changed. The child’s paragraph is a <p> too, on the same page, and the rule skipped it. (It’s black, too; the page text above can only show the upper case.) App’s CSS styles App’s template, and nothing else.
Component styles: styles and styleUrl
styles is the component’s CSS, written inside the decorator. The backticks make it a template string, so it can run over many lines. Your practice project uses inline styles because we made it with --inline-style in Part 1, so most examples replace one file.
The other way is a separate file, named with styleUrl. This is what ng new gives you without --inline-style. Here’s the same App with its CSS moved out:
// src/app/app.ts
import { Component } from '@angular/core';
import { Note } from './note';
@Component({
selector: 'app-root',
imports: [Note],
template: `
<p>Text in App</p>
<app-note />
`,
styleUrl: './app.css',
})
export class App {}
/* src/app/app.css */
p {
color: red;
text-transform: uppercase;
}
The path is relative to app.ts, so ./app.css sits next to it. The page shows the same thing:
TEXT IN APP
A note from the child
Both are compiled the same way, and both are scoped the same way. Pick by size: a few rules read well inline, and a long stylesheet is easier in its own file, where your editor helps with CSS. Older code uses styleUrls: ['./app.css'], a list. styleUrl takes one file.
How Angular keeps CSS inside a component
A browser has no idea which component a <p> came from. So how did the rule skip the child? Angular rewrites the CSS and marks the elements. This is called view encapsulation, and the default kind is emulated: Angular imitates a browser feature called Shadow DOM (more on that below) with plain attributes.
We opened the Try-this-first page in Chromium’s developer tools (F12, the Elements tab). Here’s the HTML inside <app-root>, as the browser had it, with line breaks added:
<app-root ng-version="22.3.2" _nghost-ng-c3151476031="">
<p _ngcontent-ng-c3151476031="">Text in App</p>
<app-note _ngcontent-ng-c3151476031="">
<p>A note from the child</p>
</app-note>
</app-root>
And here’s the <style> tag Angular added to the page’s <head> for App:
p[_ngcontent-ng-c3151476031] {
color: red;
text-transform: uppercase;
}
Here’s what happened:
- Angular gave
Appan id,ng-c3151476031. It’s worked out from the component’s code, so if your code differs from ours even slightly, the number will be different. - Every element in App’s template got an attribute
_ngcontent-plus that id. App’s own tag,<app-root>, got_nghost-plus the id. “Content” is what’s inside the component; “host” is the component’s own tag. - Angular rewrote
pintop[_ngcontent-ng-c3151476031]. In CSS,[name]means “has this attribute”. So the rule now means “apthat came from App’s template”. - The child’s
<p>came from Note’s template, so it doesn’t carry App’s attribute, and the rule doesn’t match.
Note has no styles at all, so Angular didn’t bother marking its paragraph. Give Note a styles and its elements get their own _ngcontent- attribute with Note’s id.
Look closely at <app-note>. It carries App’s attribute, because the tag is written in App’s template. So App’s CSS can style the <app-note> tag itself, like its margin. It can’t reach inside it.
Angular adds the component’s attribute to every selector, and to every element in its template. Only elements from the same template match. Here Note has styles of its own, so it gets its own id, xyz.
This is why component CSS can use short, plain selectors like p, h2 or .title. Two components can both have a .title rule, and neither one touches the other’s.
:host: the component’s own tag
A component’s CSS styles what’s in its template. But the component’s own tag, <app-note>, is in the parent’s template. To style it from inside, you use :host. Angular rewrites :host into [_nghost-...], the attribute on the component’s own tag.
:host(.loud) means “the host, when it has the class loud“. The parent decides by putting the class on the tag:
// src/app/note.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-note',
template: `<p>A note</p>`,
styles: `
:host {
display: block;
border-left: 4px solid gray;
padding-left: 8px;
}
:host(.loud) {
text-transform: uppercase;
}
`,
})
export class Note {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Note } from './note';
@Component({
selector: 'app-root',
imports: [Note],
template: `
<app-note />
<app-note class="loud" />
`,
})
export class App {}
The page shows:
A note
A NOTE
Two things to know about :host:
- A component’s tag is
display: inlineby default.<app-note>is a tag the browser doesn’t know, and unknown tags are inline, like a<span>. A border or a width on an inline tag looks broken. Most components that hold blocks of content start with:host { display: block; }. - The rules in
:host(...)set things on the tag, and the text inside inherits them.text-transformandcolorare inherited in CSS, so the<p>inside picks them up.
You may also meet :host-context(.dark), which means “the host, when some element above it has the class dark“. Angular’s compiler still supports it, though Angular’s own docs note that browsers treat it as deprecated. The CSS custom properties below do the same job in plain CSS.
The host setting: classes on your own tag
In that example, the parent had to know to write class="loud". Usually the component should decide, from its own inputs. The host setting in @Component adds bindings to the component’s own tag, written the way you’d write them in a template:
// src/app/note.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-note',
template: `<p>A note</p>`,
styles: `
:host {
display: block;
}
:host(.loud) {
text-transform: uppercase;
}
`,
host: { '[class.loud]': 'loud()' },
})
export class Note {
readonly loud = input(false);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Note } from './note';
@Component({
selector: 'app-root',
imports: [Note],
template: `
<app-note [loud]="loud()" />
<button (click)="loud.set(!loud())">Toggle</button>
`,
})
export class App {
protected readonly loud = signal(false);
}
host: { '[class.loud]': 'loud()' } is [class.loud]="loud()", put on <app-note> by Note itself. The key is the binding, and the value is the expression, in quotes. The expression runs against Note, so loud() is Note’s input.
Click Toggle. The page shows:
A NOTE
Toggle
and the tag now has the class:
<app-note class="loud"><p>A note</p></app-note>
(We’ve left out Angular’s _ngcontent and _nghost attributes here and in the HTML below, to keep it readable.)
The parent passes data, the child decides how it looks. The host setting also takes [style.x], [attr.x] and plain attributes like role: 'alert', and (event) listeners. Part 11 covers listeners.
CSS custom properties: theming a child from outside
Encapsulation stops a parent’s selectors from reaching into a child. That’s what you want most of the time. But sometimes the parent needs a say: “this badge should be purple”. You could add an input for every colour. There’s a cleaner way that’s plain CSS.
A CSS custom property is a variable in CSS. Its name starts with two dashes, --accent, and you read it with var(--accent). var(--accent, gray) means “use --accent, or gray if nobody set it”. Custom properties are inherited, like color: set one on a tag, and everything inside it can read it. Encapsulation only rewrites selectors, so inheritance passes straight through it.
So the child reads --accent, and the parent sets it on the child’s tag:
// src/app/badge.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-badge',
template: `{{ label() }}`,
styles: `
:host {
border: 2px solid var(--accent, gray);
color: var(--accent, gray);
padding: 0 6px;
margin-right: 4px;
}
`,
})
export class Badge {
readonly label = input.required<string>();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Badge } from './badge';
@Component({
selector: 'app-root',
imports: [Badge],
template: `
<app-badge label="Draft" />
<app-badge label="New" [style.--accent]="'purple'" />
<app-badge label="Sale" class="hot" />
`,
styles: `
.hot {
--accent: crimson;
}
`,
})
export class App {}
The page shows:
DraftNewSale
and the HTML is:
<app-badge label="Draft">Draft</app-badge>
<app-badge label="New" style="--accent: purple;">New</app-badge>
<app-badge label="Sale" class="hot">Sale</app-badge>
The badges are inline, so they share one line. Angular drops the spaces between tags in a template, so the page text runs them together; the margin-right keeps them apart on the screen. In the browser, Draft is gray, New is purple and Sale is crimson. (We checked the colours in the developer tools; the page text can’t show them.) Two ways of setting the property:
[style.--accent]="'purple'"binds the custom property straight onto the tag, like any[style.x]. Note the quotes inside the quotes:'purple'is a string..hot { --accent: crimson; }is in App’s CSS. It matches because<app-badge>sits in App’s template and carries App’s attribute, as the figure showed.
The child’s CSS still decides what the accent is used for: a border and the text here, maybe a background somewhere else. The parent only picks the colour. That split is what makes a component easy to theme.
[class] and [style] with objects
Part 2 showed [class] with a string or an object. [style] takes an object too. Keys are CSS property names, values are CSS values:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p [style]="boxStyle()">Size {{ size() }}</p>
<button (click)="size.set(size() + 4)">Bigger</button>
`,
})
export class App {
protected readonly size = signal(16);
protected readonly boxStyle = computed(() => ({
'font-size': this.size() + 'px',
border: '1px solid gray',
}));
}
Click Bigger. The page shows:
Size 20
Bigger
and the paragraph is:
<p style="border: 1px solid gray; font-size: 20px;">Size 20</p>
The unit goes in the value, '20px'. The .px trick from [style.width.px] only works in that one-style form. We tried { 'font-size.px': 20 } in an object, and the browser got no font size at all, with no error. Building the object in a computed keeps the template short and gives Angular a new object only when size changes.
Global styles: src/styles.css
Some CSS should reach everything: a font for the whole page, a body margin, a reset. That goes in src/styles.css, which ng new made in Part 1. Angular adds it to the page as a normal stylesheet, with no rewriting:
/* You can add global styles to this file, and also import other style files */
body {
font-family: system-ui, sans-serif;
margin: 16px;
}
A rule in styles.css matches every element in every component, because nothing is added to its selectors. Keep it to things that really are global. A .card rule in there styles every .card in the app, and that’s the problem encapsulation solved. (We checked: a p { color: purple; } in styles.css coloured every paragraph, in App and in children.)
Turning encapsulation off, and other ways out
@Component has an encapsulation setting. It takes a value from ViewEncapsulation. Angular 22 has four, and three of them matter day to day:
ViewEncapsulation.Emulatedis the default, the attribute rewriting above. You never write it.ViewEncapsulation.Noneturns the rewriting off. The component’s CSS becomes global CSS for as long as the component is on the page.ViewEncapsulation.ShadowDomuses the browser’s real Shadow DOM: the component’s content lives in a separate tree. Its CSS can’t leak out, and selectors insrc/styles.cssdon’t match elements inside it. Inherited properties likefont-familyandcolorstill flow in, and Angular copies other components’ styles into it. That changes how global styles, fonts and some tests behave. Reach for it only when you need that wall, for example in a widget embedded in pages you don’t control.
The fourth value, ViewEncapsulation.ExperimentalIsolatedShadowDom, is marked experimental since Angular 21. It’s Shadow DOM without the copying: only the component’s own styles apply inside it. Leave it alone until it’s stable.
Here’s what None does:
// src/app/loud.ts
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-loud',
template: `<p>Loud</p>`,
styles: `
p {
text-transform: uppercase;
}
`,
encapsulation: ViewEncapsulation.None,
})
export class Loud {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Loud } from './loud';
@Component({
selector: 'app-root',
imports: [Loud],
template: `
<p>App text</p>
<app-loud />
`,
})
export class App {}
The page shows:
APP TEXT
LOUD
Loud‘s rule reached App’s paragraph, which isn’t even in its template. That’s None: one component’s CSS styling another.
There’s one more way out you’ll see in existing code, ::ng-deep. It switches the rewriting off for the rest of a selector:
:host ::ng-deep p {
color: red;
}
Angular turns that into [_nghost-...] p: any p anywhere inside this component, including inside its children. (A ::ng-deep with no :host in front becomes plain global CSS.) Angular’s styling guide says the team “strongly discourages new use of ::ng-deep” and keeps it for backwards compatibility. If a parent needs to change how a child looks, give the child an input or a custom property.
Animations: animate.enter and animate.leave
When @if shows an element, it appears at once. Angular 22 has two template features to animate an element as it arrives and leaves, using plain CSS:
animate.enter="fade-in"adds the classfade-inwhen the element is added to the page, and removes the class when its CSS animation or transition has finished (or straight away if there is none).animate.leave="fade-out"adds the classfade-outwhen the element is about to be removed, waits for the animation to finish, and only then removes the element.
The CSS does the actual animating:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button (click)="show.set(!show())">Toggle</button>
@if (show()) {
<p animate.enter="fade-in" animate.leave="fade-out">Hello</p>
}
`,
styles: `
.fade-in {
animation: fade 1s;
}
.fade-out {
animation: fade 1s reverse;
}
@keyframes fade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
`,
})
export class App {
protected readonly show = signal(false);
}
@keyframes fade is a CSS animation from invisible (opacity: 0) to fully visible. .fade-in plays it over one second; .fade-out plays it backwards.
Click Toggle. Straight away, the paragraph is there with the class:
<p class="fade-in">Hello</p>
A second later, the animation has finished and Angular has taken the class off again:
<p class="">Hello</p>
Now click Toggle again. show() is false, but the paragraph is still in the page, fading out:
Toggle
Hello
After the animation, it’s gone:
Toggle
The animation classes live in the component’s CSS, so they’re scoped like any other rule. You import nothing for this; animate.enter and animate.leave are part of the template language. You can also bind them, [animate.enter]="enterClass()", to pick the class from a signal.
Worked example: a themable alert
Let’s build an alert box with three kinds: info, warning and error. The kind is an input. The component puts the kind on its own tag as a class, picks an accent colour per kind, and lets a parent override the accent.
// src/app/alert.ts
import { Component, input } from '@angular/core';
export type AlertKind = 'info' | 'warn' | 'error';
@Component({
selector: 'app-alert',
template: `
<strong>{{ title() }}</strong>
<span>{{ text() }}</span>
`,
styles: `
:host {
--accent: steelblue;
display: block;
border-left: 4px solid var(--accent);
padding: 4px 8px;
margin-bottom: 8px;
}
:host(.warn) {
--accent: darkorange;
}
:host(.error) {
--accent: crimson;
}
strong {
color: var(--accent);
margin-right: 6px;
}
`,
host: { role: 'alert', '[class]': 'kind()' },
})
export class Alert {
readonly kind = input<AlertKind>('info');
readonly title = input.required<string>();
readonly text = input('');
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Alert } from './alert';
@Component({
selector: 'app-root',
imports: [Alert],
template: `
<app-alert title="Saved" text="Your changes are stored." />
<app-alert kind="warn" title="Careful" text="This can't be undone." />
<app-alert kind="error" title="Failed" text="Try again." />
<app-alert class="brand" title="New" text="Dark mode is here." />
`,
styles: `
.brand {
--accent: rebeccapurple;
}
`,
})
export class App {}
Some things to notice:
export type AlertKind = 'info' | 'warn' | 'error'is a TypeScript union type: a value that must be one of those three strings.kind="danger"in a template would fail to build.host: { role: 'alert', '[class]': 'kind()' }sets a plain attribute,role="alert", which tells screen readers this is an alert. It also binds[class]to the kind. A[class]host binding adds its classes without wiping out classes the parent wrote, likebrand.:hostsets--accentto a default, and:host(.warn)and:host(.error)change it. Everything else readsvar(--accent), so the border and the title colour always agree.- App’s
.brandrule sets--accenton the last alert’s tag. App’s rule and:hostboth set the property on the same tag. App’s rule wins because its selector is more specific (a class plus App’s attribute, against Alert’s attribute alone).
The page shows:
SavedYour changes are stored.
CarefulThis can't be undone.
FailedTry again.
NewDark mode is here.
The title and the text run together in the page text, as the badges did; on the screen, the title’s margin-right separates them. The tags are:
<app-alert role="alert" title="Saved" text="Your changes are stored." class="info">
<app-alert role="alert" kind="warn" title="Careful" text="This can't be undone." class="warn">
<app-alert role="alert" title="New" text="Dark mode is here." class="brand info">
In the browser, the four borders and titles are steel blue, dark orange, crimson and purple. (Checked in the developer tools again.) To add a kind, you add one :host(.success) rule and one string to the union type. The parent’s templates don’t change.
Worked example: two errors in one build
A teammate moves Alert’s CSS into its own file, renames the input kind to variant in the class, and builds. They forgot two things: they named the new file alert.component.css, the way older projects did, and they didn’t update the host binding.
// src/app/alert.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-alert',
template: `<strong>{{ title() }}</strong>`,
styleUrl: './alert.css',
host: { '[class]': 'kind()' },
})
export class Alert {
readonly variant = input<'info' | 'warn'>('info');
readonly title = input.required<string>();
}
/* src/app/alert.component.css */
:host {
display: block;
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Alert } from './alert';
@Component({
selector: 'app-root',
imports: [Alert],
template: `<app-alert title="Saved" />`,
})
export class App {}
ng serve prints two errors:
✘ [ERROR] NG2008: Could not find stylesheet file './alert.css'. [plugin angular-compiler]
7 │ styleUrl: './alert.css',
✘ [ERROR] TS2339: Property 'kind' does not exist on type 'Alert'. [plugin angular-compiler]
8 │ host: { '[class]': 'kind()' },
Read them one at a time:
- NG2008 is Angular’s compiler saying the file named in
styleUrlisn’t there. The path is relative toalert.ts, and the file on disk isalert.component.css. Rename the file toalert.css(or changestyleUrl; the style guide prefers names without.component). - TS2339 points into the
hostsetting. The string'kind()'looks like plain text, but Angular type-checks it against the class, the same as a template.Alerthas nokindany more. Change the expression tovariant().
Errors in host are easy to miss, because the expression sits inside quotes and your editor may not underline it. The build checks it anyway. With both fixes:
// src/app/alert.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-alert',
template: `<strong>{{ title() }}</strong>`,
styleUrl: './alert.css',
host: { '[class]': 'variant()' },
})
export class Alert {
readonly variant = input<'info' | 'warn'>('info');
readonly title = input.required<string>();
}
/* src/app/alert.css */
:host {
display: block;
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Alert } from './alert';
@Component({
selector: 'app-root',
imports: [Alert],
template: `<app-alert title="Saved" />`,
})
export class App {}
The page shows:
Saved
and the tag has its class:
<app-alert title="Saved" class="info"><strong>Saved</strong></app-alert>
A typo in the binding’s name, rather than its expression, fails too. '[clas.info]' gives NG8002, Can't bind to 'clas.info' since it isn't a known property of 'app-alert', the same error a template gives for an unknown property.
In older code
Before the host setting was the usual way, components put bindings on their own tag with decorators on class members: @HostBinding('class.loud') loud = false; and @HostListener('click') onClick() {...}. Angular’s guide says to always prefer the host setting, and that these decorators exist only for backwards compatibility. You’ll also see [ngClass]="{ loud: isLoud }" and [ngStyle]="{ 'font-size': size + 'px' }", from NgClass and NgStyle in @angular/common, imported into the component. They still work. The built-in [class] and [style] bindings do the same job with nothing to import. Older components used the animations setting with trigger() and @angular/animations. That’s deprecated since Angular 20.2, in favour of animate.enter and animate.leave.
Best practices
- Write short, plain selectors in component CSS.
p,.titleandh2are safe, because Angular scopes them. It replaces long, unique class names like.user-card__titlethat only exist to avoid clashes. - Start a component that holds blocks with
:host { display: block; }. Otherwise its tag is inline, and borders, widths and margins look wrong. It replaces wrapping the whole template in an extra<div>. - Let the component style its own tag through
host.host: { '[class.loud]': 'loud()' }plus a:host(.loud)rule keeps the look inside the component. It replaces parents writing classes they have to know about, and@HostBinding. - Theme children with CSS custom properties. The child reads
var(--accent, default); the parent sets--accenton the tag. It replaces::ng-deepandViewEncapsulation.None, which reach in and break when the child changes. - Keep
styles.cssfor what’s truly global. Fonts, the body, a reset. Component looks go in the component, where only that component sees them.
Tips and traps
- A parent’s rule doesn’t reach a child. You write
.title { ... }in App and the child’s.titledoesn’t change, with no error. That’s encapsulation working. Put the rule in the child, or give the child a custom property or an input. - A border or width does nothing on a component. The tag is inline. Add
:host { display: block; }(orinline-block,flex) in the child. styleUrlpointing at a missing file. The build fails with NG2008,Could not find stylesheet file. Check the file name and that the path is relative to the.tsfile.- A wrong name in a
hostexpression. It fails with TS2339 or TS2551, pointing at the string inhost. The expression is checked against the class, like a template. - A unit in a
[style]object key.{ 'font-size.px': 20 }sets nothing and reports nothing. Put the unit in the value:{ 'font-size': '20px' }. - A
ViewEncapsulation.Nonecomponent that restyles other pages. Its CSS is global while it’s on the screen, so other components change when it appears. Keep encapsulation on, and use a custom property for what a parent needs to change.
Angular scopes a component’s CSS to its own template; to style its own tag use
:host, and to let a parent theme it, use a CSS custom property.
Exercises
Exercise 1. App wants every title upper case, so it has a .title rule. Only one title changes. Why? Fix it so both titles are upper case, without ::ng-deep or ViewEncapsulation.None.
// src/app/card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `<h2 class="title">Card title</h2>`,
})
export class Card {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<h1 class="title">Page title</h1>
<app-card />
`,
styles: `
.title {
text-transform: uppercase;
}
`,
})
export class App {}
PAGE TITLE
Card title
Exercise 2. Write a Chip component, app-chip, with a text input label and a boolean input selected that starts false. When selected is true, the chip’s own tag should get the class selected, and a :host(.selected) rule should make the text upper case. In App, show one chip labelled “Tea”, and a Select button that toggles it.
Exercise 3. Without running it, say what the page shows after the page loads, after one click on Toggle, and after a second click. Shout uses ViewEncapsulation.None.
// src/app/shout.ts
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-shout',
template: `<p>Shout</p>`,
styles: `
p {
text-transform: uppercase;
}
`,
encapsulation: ViewEncapsulation.None,
})
export class Shout {}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Shout } from './shout';
@Component({
selector: 'app-root',
imports: [Shout],
template: `
<p>App text</p>
<button (click)="show.set(!show())">Toggle</button>
@if (show()) {
<app-shout />
}
`,
})
export class App {
protected readonly show = signal(false);
}
Answers
1. App’s .title is rewritten to .title[_ngcontent-...] with App’s id. The card’s <h2> came from Card’s template, so it doesn’t carry App’s attribute. Give Card its own rule:
// src/app/card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `<h2 class="title">Card title</h2>`,
styles: `
.title {
text-transform: uppercase;
}
`,
})
export class Card {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<h1 class="title">Page title</h1>
<app-card />
`,
styles: `
.title {
text-transform: uppercase;
}
`,
})
export class App {}
The page shows:
PAGE TITLE
CARD TITLE
If every title in the whole app should be upper case, a .title rule in src/styles.css works too. That’s a choice about the whole app, so make it on purpose.
2. The host setting binds the class from the input:
// src/app/chip.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-chip',
template: `{{ label() }}`,
styles: `
:host {
border: 1px solid gray;
padding: 0 6px;
}
:host(.selected) {
text-transform: uppercase;
}
`,
host: { '[class.selected]': 'selected()' },
})
export class Chip {
readonly label = input.required<string>();
readonly selected = input(false);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Chip } from './chip';
@Component({
selector: 'app-root',
imports: [Chip],
template: `
<app-chip label="Tea" [selected]="selected()" />
<button (click)="selected.set(!selected())">Select</button>
`,
})
export class App {
protected readonly selected = signal(false);
}
Click Select. The page shows:
TEASelect
and the chip’s tag is <app-chip label="Tea" class="selected">:
The chip and the button are both inline, so they share a line, and the page text runs them together.
3. At first, Shout isn’t on the page, so its CSS isn’t either: App text. After one click, Shout is created, its CSS is added to the page as a global rule, and every p is upper case, App’s included. After the second click, Shout is destroyed and Angular removes its CSS again, so App’s text goes back to normal. Here’s the run:
// src/app/shout.ts
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-shout',
template: `<p>Shout</p>`,
styles: `
p {
text-transform: uppercase;
}
`,
encapsulation: ViewEncapsulation.None,
})
export class Shout {}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Shout } from './shout';
@Component({
selector: 'app-root',
imports: [Shout],
template: `
<p>App text</p>
<button (click)="show.set(!show())">Toggle</button>
@if (show()) {
<app-shout />
}
`,
})
export class App {
protected readonly show = signal(false);
}
When the page loads, it shows:
App text
Toggle
After one click on Toggle:
APP TEXT
Toggle
SHOUT
After a second click:
App text
Toggle
This is why None bugs are hard to find: a page looks different depending on what else happened to be on the screen.
What’s next
Our components now take inputs, send events and carry their own look. In Part 8, we go back to signals: effect for side effects (and why it’s rarely the answer), linkedSignal, and untracked.