Cours Angular · Module 13: UI et styles
Le style dans Angular - La cérémonie du thé
Dans cette leçon4
Le style est comme la cérémonie du thé 茶道 (chado) - il exige harmonie, simplicité et attention à chaque détail. Dans un pavillon de thé traditionnel, chaque élément a sa place et sa signification. Il en va de même pour ton application !
Encapsulation des styles
Angular propose trois modes d'encapsulation des styles :
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 {}Modes d'encapsulation :
| Mode | Description |
|---|---|
| Emulated | Encapsulation émulée (par défaut) - ajoute des attributs uniques |
| ShadowDom | Véritable Shadow DOM - isolation complète |
| None | Aucune encapsulation - les styles sont globaux |
Fichiers de style
@Component({
selector: 'app-dojo',
templateUrl: './dojo.component.html',
styleUrls: ['./dojo.component.scss'] // External SCSS file
})
export class DojoComponent {}SCSS/SASS dans 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;
}
}Variables CSS et thématisation
// 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 de cette leçon : 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>Cérémonie du Thé - Animations Angular</h1>
<section class="fade-demo">
<h2>Fondu entrant/sortant</h2>
<button (click)="toggleMessage()">
{{ showMessage() ? '{{ showMessage() ? 'Masquer' : 'Afficher' }} le message
</button>
@if (showMessage()) {
<div class="message-box" @fadeInOut>
<p>Bienvenue à la cérémonie du thé, guerrier !</p>
</div>
}
</section>
<section class="list-demo">
<h2>Liste avec Stagger</h2>
<button (click)="addSamurai()">Ajouter un samouraï</button>
<button (click)="clearSamurai()">Effacer</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>Déplier/Replier</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>Code d'animation</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: 'À propos de la cérémonie du thé', expanded: false, content: "La cérémonie du thé (chado) est une tradition japonaise de préparation et de service du thé matcha. Elle symbolise l'harmonie, le respect, la pureté et la tranquillité." },
{ id: 2, title: 'Code Bushido', expanded: false, content: "Le Bushido est le code d'honneur des samouraïs, regroupant des valeurs telles que la loyauté, le courage, l'honneur, le respect et l'honnêteté." },
{ id: 3, title: 'Architecture des châteaux', expanded: false, content: 'Les châteaux japonais (shiro) sont des fortifications construites principalement en bois et en pierre. Ils comportent des tours à plusieurs niveaux et des systèmes défensifs complexes.' }
]);
animationCode = `// Définition de l'animation dans @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 })
])
])
]
// Utilisation dans le 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;
}Tu as repéré une erreur dans cette leçon ?
Teste tes connaissances
Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.
1. Que fait ViewEncapsulation.Emulated dans Angular ?
2. Quel mode de ViewEncapsulation rend les styles d'un composant globaux (sans isolation) ?
Voici 2 des 3 questions de cette leçon. Réponds aux autres dans le jeu.
Tâches pratiques dans le jeu
- Clique dans l'ordre
Construis un sélecteur qui applique un style à l'élément hôte du composant avec la classe .highlighted : :host(.highlighted)
- Éditeur de code
Complète le composant avec sa propre encapsulation des styles.
- Tri horizontal
Ordonne sur une seule ligne la déclaration d'une variable SCSS contenant la couleur du clan.
- Tri vertical
Ordonne les lignes d'une règle SCSS qui inclut un mixin et définit un padding (de haut en bas dans l'éditeur).