Kurs Angular · Moduł 13: UI i stylowanie

Stylowanie w Angular - Ceremonia Herbaciana

2 min czytania ·
W tej lekcji4

Stylowanie to jak ceremonia herbaciana 茶道 (chado) - wymaga harmonii, prostoty i dbałości o każdy detal. W tradycyjnym pawilonie herbacianym każdy element ma swoje miejsce i znaczenie. Tak samo w Twojej aplikacji!

Enkapsulacja Stylów

Angular oferuje trzy tryby enkapsulacji stylów:

import { ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-tea-house',
  encapsulation: ViewEncapsulation.Emulated,  // Domyślne
  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 {
      /* Style lokalne dla tego komponentu */
    }
  `]
})
export class TeaHouseComponent {}

Tryby enkapsulacji:

TrybOpis
EmulatedSymulowana enkapsulacja (domyślna) - dodaje unikalne atrybuty
ShadowDomPrawdziwy Shadow DOM - pełna izolacja
NoneBrak enkapsulacji - style są globalne

Pliki Stylów

@Component({
  selector: 'app-dojo',
  templateUrl: './dojo.component.html',
  styleUrls: ['./dojo.component.scss']  // Zewnętrzny plik SCSS
})
export class DojoComponent {}

SCSS/SASS w Angular

// dojo.component.scss

// Zmienne
$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);
  }
}

// Komponenty
.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 z Theming

// styles.scss (globalny)
: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;
}

// Użycie w komponencie
.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'
    );
  }
}
Kod do tej lekcji: 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: [
    // Animacja fade
    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)' }))
      ])
    ]),

    // Animacja listy z stagger
    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 })
      ])
    ]),

    // Animacja toggle
    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>Ceremonia Herbaciana - Animacje Angular</h1>

      <section class="fade-demo">
        <h2>Fade In/Out</h2>
        <button (click)="toggleMessage()">
          {{ showMessage() ? 'Ukryj' : 'Pokaż' }} wiadomość
        </button>

        @if (showMessage()) {
          <div class="message-box" @fadeInOut>
            <p>Witaj w ceremonii herbacianej, wojowniku!</p>
          </div>
        }
      </section>

      <section class="list-demo">
        <h2>Lista z Stagger</h2>
        <button (click)="addSamurai()">Dodaj Samuraja</button>
        <button (click)="clearSamurai()">Wyczyść</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>Kod animacji</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: 'O ceremonii herbacianej', expanded: false, content: 'Ceremonia herbaciana (chado) to japońska tradycja przygotowywania i podawania herbaty matcha. Symbolizuje harmonię, szacunek, czystość i spokój.' },
    { id: 2, title: 'Kodeks Bushido', expanded: false, content: 'Bushido to kodeks honorowy samurajów, obejmujący wartości takie jak lojalność, odwaga, honor, szacunek i uczciwość.' },
    { id: 3, title: 'Architektura zamków', expanded: false, content: 'Japońskie zamki (shiro) to fortyfikacje budowane głównie z drewna i kamienia. Charakteryzują się wielopoziomowymi wieżami i skomplikowanymi systemami obronnymi.' }
  ]);

  animationCode = `// Definicja animacji w @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 })
    ])
  ])
]

// Użycie w template
@if (showMessage()) {
  <div @fadeInOut>Wiadomość</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;
}

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Co robi ViewEncapsulation.Emulated w Angular?

  2. 2. Który tryb ViewEncapsulation sprawia, że style komponentu stają się globalne (bez izolacji)?

To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Klikanie w kolejności

    Zbuduj selektor stylujący element-gospodarz komponentu z klasą .highlighted: :host(.highlighted)

  • Edytor kodu

    Uzupełnij komponent z własną enkapsulacją stylów.

  • Układanie w poziomie

    Ułóż w jednej linii deklarację zmiennej SCSS z kolorem klanu.

  • Układanie w pionie

    Uporządkuj linie reguły SCSS, która dołącza mixin i ustawia padding (kolejność od góry do dołu w edytorze).

  1. PytanieViewEncapsulation
  2. PytanieTryb globalnych stylów
  3. Kliknij w kolejnościSelektor :host
  4. Zadanie z kodemPraktyka: Enkapsulacja stylów
  5. Ułóż w kolejnościDefinicja zmiennej SCSS
  6. PytanieCSS Variables i theming
  7. Ułóż w kolejnościReguła SCSS z mixinem

Przydatne artykuły