Angular course · Module 13: UI and Styling
Styling in Angular - The Tea Ceremony
In this lesson4
Styling is like the tea ceremony 茶道 (chado) - it requires harmony, simplicity, and attention to every detail. In a traditional tea pavilion, every element has its place and meaning. The same applies to your application!
Style Encapsulation
Angular offers three style encapsulation modes:
import { ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-tea-house',
encapsulation: ViewEncapsulation.Emulated, // Default
template: `<div class="tea-room">...</div>`,
styles: [`
:host {
display: block;
padding: 20px;
background: #f5f5dc;
}
:host(.highlighted) {
border: 2px solid gold;
}
:host-context(.dark-theme) {
background: #2d2d2d;
}
.tea-room {
/* Local styles for this component */
}
`]
})
export class TeaHouseComponent {}Encapsulation modes:
| Mode | Description |
|---|---|
| Emulated | Emulated encapsulation (default) - adds unique attributes |
| ShadowDom | Real Shadow DOM - full isolation |
| None | No encapsulation - styles are global |
Style Files
@Component({
selector: 'app-dojo',
templateUrl: './dojo.component.html',
styleUrls: ['./dojo.component.scss'] // External SCSS file
})
export class DojoComponent {}SCSS/SASS in Angular
// dojo.component.scss
// Variables
$primary-color: #c41e3a;
$samurai-gold: #ffd700;
// Mixins
@mixin card-shadow {
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: box-shadow 0.3s ease;
&:hover {
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2);
}
}
// Components
.samurai-card {
@include card-shadow;
padding: 1rem;
border-radius: 8px;
background: linear-gradient(135deg, #fff 0%, #f0f0f0 100%);
&__header {
color: $primary-color;
border-bottom: 2px solid $samurai-gold;
}
&__content {
margin-top: 1rem;
}
&--highlighted {
border: 2px solid $samurai-gold;
}
}CSS Variables with Theming
// styles.scss (global)
:root {
--primary-color: #c41e3a;
--secondary-color: #1e3a8a;
--background: #ffffff;
--text-color: #333333;
--border-radius: 8px;
}
[data-theme="dark"] {
--primary-color: #ff6b6b;
--secondary-color: #4dabf7;
--background: #1a1a2e;
--text-color: #eaeaea;
}
// Usage in component
.samurai-card {
background: var(--background);
color: var(--text-color);
border-radius: var(--border-radius);
}// Theme service
@Injectable({ providedIn: 'root' })
export class ThemeService {
private isDark = signal(false);
toggleTheme(): void {
this.isDark.update(v => !v);
document.documentElement.setAttribute(
'data-theme',
this.isDark() ? 'dark' : 'light'
);
}
}Code for this lesson: src/app/app.component.ts
import { Component, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { trigger, state, style, animate, transition, query, stagger } from '@angular/animations';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
animations: [
// Fade animation
trigger('fadeInOut', [
transition(':enter', [
style({ opacity: 0, transform: 'translateY(-20px)' }),
animate('300ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
]),
transition(':leave', [
animate('200ms ease-in', style({ opacity: 0, transform: 'translateY(20px)' }))
])
]),
// Staggered list animation
trigger('listAnimation', [
transition('* => *', [
query(':enter', [
style({ opacity: 0, transform: 'translateX(-50px)' }),
stagger(100, [
animate('300ms ease-out', style({ opacity: 1, transform: 'translateX(0)' }))
])
], { optional: true })
])
]),
// Toggle animation
trigger('expandCollapse', [
state('collapsed', style({
height: '0',
overflow: 'hidden',
opacity: 0
})),
state('expanded', style({
height: '*',
opacity: 1
})),
transition('collapsed <=> expanded', [
animate('300ms ease-in-out')
])
])
],
template: `
<div class="tea-ceremony">
<h1>Tea Ceremony - Angular Animations</h1>
<section class="fade-demo">
<h2>Fade In/Out</h2>
<button (click)="toggleMessage()">
{{ showMessage() ? '{{ showMessage() ? 'Hide' : 'Show' }} message
</button>
@if (showMessage()) {
<div class="message-box" @fadeInOut>
<p>Welcome to the tea ceremony, warrior!</p>
</div>
}
</section>
<section class="list-demo">
<h2>List with Stagger</h2>
<button (click)="addSamurai()">Add Samurai</button>
<button (click)="clearSamurai()">Clear</button>
<div class="samurai-list" [@listAnimation]="samuraiList().length">
@for (samurai of samuraiList(); track samurai.id) {
<div class="samurai-card" @fadeInOut>
<span class="rank">{{ samurai.rank }}</span>
<span class="name">{{ samurai.name }}</span>
<button class="remove" (click)="removeSamurai(samurai.id)">×</button>
</div>
}
</div>
</section>
<section class="expand-demo">
<h2>Expand/Collapse</h2>
@for (item of accordionItems(); track item.id) {
<div class="accordion-item">
<div class="accordion-header" (click)="toggleAccordion(item.id)">
<span>{{ item.title }}</span>
<span class="icon">{{ item.expanded ? '▼' : '▶' }}</span>
</div>
<div class="accordion-content"
[@expandCollapse]="item.expanded ? 'expanded' : 'collapsed'">
<p>{{ item.content }}</p>
</div>
</div>
}
</section>
<section class="code-section">
<h2>Animation code</h2>
<pre><code>{{ animationCode }}</code></pre>
</section>
</div>
`,
styles: [`
.tea-ceremony {
font-family: 'Segoe UI', sans-serif;
padding: 20px;
background: linear-gradient(135deg, #1a472a 0%, #2d5a3d 100%);
min-height: 100vh;
color: #f5f5dc;
}
h1 {
text-align: center;
color: #90ee90;
}
h2 {
color: #90ee90;
border-bottom: 2px solid #90ee90;
padding-bottom: 10px;
}
section {
background: rgba(0,0,0,0.3);
border-radius: 10px;
padding: 20px;
margin: 20px 0;
}
button {
padding: 10px 20px;
background: #90ee90;
color: #1a472a;
border: none;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
margin: 5px;
}
button:hover {
background: #7ccd7c;
}
.message-box {
background: rgba(144, 238, 144, 0.2);
border: 2px solid #90ee90;
border-radius: 10px;
padding: 20px;
margin-top: 15px;
text-align: center;
}
.samurai-list {
margin-top: 15px;
}
.samurai-card {
display: flex;
align-items: center;
gap: 15px;
padding: 12px;
margin: 8px 0;
background: rgba(0,0,0,0.3);
border-radius: 8px;
border-left: 4px solid #90ee90;
}
.samurai-card .rank {
background: #90ee90;
color: #1a472a;
padding: 4px 10px;
border-radius: 4px;
font-size: 0.85em;
}
.samurai-card .name {
flex: 1;
}
.samurai-card .remove {
padding: 5px 10px;
background: #e74c3c;
color: white;
border-radius: 3px;
}
.accordion-item {
margin: 10px 0;
border-radius: 8px;
overflow: hidden;
}
.accordion-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
background: rgba(144, 238, 144, 0.2);
cursor: pointer;
transition: background 0.3s;
}
.accordion-header:hover {
background: rgba(144, 238, 144, 0.3);
}
.accordion-content {
background: rgba(0,0,0,0.3);
padding: 0 15px;
}
.accordion-content p {
margin: 15px 0;
}
pre {
background: #0a1f0f;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
border-left: 4px solid #90ee90;
}
code {
color: #f5f5dc;
font-family: 'Fira Code', monospace;
font-size: 0.85em;
}
`]
})
export class AppComponent {
showMessage = signal(false);
nextId = signal(1);
samuraiList = signal<Samurai[]>([]);
accordionItems = signal([
{ id: 1, title: 'About the tea ceremony', expanded: false, content: 'The tea ceremony (chado) is a Japanese tradition of preparing and serving matcha tea. It symbolizes harmony, respect, purity, and tranquility.' },
{ id: 2, title: 'Bushido Code', expanded: false, content: 'Bushido is the samurai code of honor, encompassing values such as loyalty, courage, honor, respect, and honesty.' },
{ id: 3, title: 'Castle architecture', expanded: false, content: 'Japanese castles (shiro) are fortifications built mainly from wood and stone. They feature multi-level towers and complex defensive systems.' }
]);
animationCode = `// Animation definition in @Component
animations: [
trigger('fadeInOut', [
transition(':enter', [
style({ opacity: 0, transform: 'translateY(-20px)' }),
animate('300ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
]),
transition(':leave', [
animate('200ms ease-in', style({ opacity: 0, transform: 'translateY(20px)' }))
])
]),
trigger('listAnimation', [
transition('* => *', [
query(':enter', [
style({ opacity: 0, transform: 'translateX(-50px)' }),
stagger(100, [
animate('300ms ease-out', style({ opacity: 1, transform: 'translateX(0)' }))
])
], { optional: true })
])
])
]
// Usage in template
@if (showMessage()) {
<div @fadeInOut>Message</div>
}
<div [@listAnimation]="items.length">
@for (item of items; track item.id) {
<div @fadeInOut>{{ item.name }}</div>
}
</div>`;
toggleMessage(): void {
this.showMessage.update(v => !v);
}
addSamurai(): void {
const names = ['Musashi', 'Kojiro', 'Hanzo', 'Jubei', 'Masamune', 'Nobunaga'];
const ranks = ['Ronin', 'Hatamoto', 'Daimyo', 'Shogun'];
const newSamurai: Samurai = {
id: this.nextId(),
name: names[Math.floor(Math.random() * names.length)],
rank: ranks[Math.floor(Math.random() * ranks.length)]
};
this.samuraiList.update(list => [...list, newSamurai]);
this.nextId.update(id => id + 1);
}
removeSamurai(id: number): void {
this.samuraiList.update(list => list.filter(s => s.id !== id));
}
clearSamurai(): void {
this.samuraiList.set([]);
}
toggleAccordion(id: number): void {
this.accordionItems.update(items =>
items.map(item =>
item.id === id ? { ...item, expanded: !item.expanded } : item
)
);
}
}
interface Samurai {
id: number;
name: string;
rank: string;
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does ViewEncapsulation.Emulated do in Angular?
2. Which ViewEncapsulation mode makes a component's styles global (no isolation)?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Click in order
Build a selector that styles the component's host element with the .highlighted class: :host(.highlighted)
- Code editor
Complete the component with its own style encapsulation.
- Horizontal ordering
Arrange on a single line the declaration of an SCSS variable holding the clan color.
- Vertical ordering
Order the lines of an SCSS rule that includes a mixin and sets padding (top-to-bottom order in the editor).