Kurs Angular · Moduł 14: Zaawansowane wzorce

Zaawansowane Wzorce - Szczyt Góry Fuji

2 min czytania ·
W tej lekcji4

Na szczycie góry Fuji 富士山 - świętej góry Japonii - poznasz najwyższe techniki sztuki miecza. To ostateczna próba przed uzyskaniem tytułu mistrza Angular!

Content Projection (ng-content)

Content Projection to jak technika przekazywania miecza następcy - pozwala komponentom przyjmować dowolną treść:

// Prosty slot
@Component({
  selector: 'app-panel',
  template: `
    <div class="panel">
      <ng-content></ng-content>
    </div>
  `
})
export class PanelComponent {}

// Użycie
<app-panel>
  <p>Dowolna treść</p>
</app-panel>

Multi-Slot Content Projection

@Component({
  selector: 'app-card',
  template: `
    <article class="card">
      <header class="card-header">
        <ng-content select="[card-header]"></ng-content>
      </header>

      <main class="card-body">
        <ng-content></ng-content>
      </main>

      <footer class="card-footer">
        <ng-content select="[card-footer]"></ng-content>
      </footer>
    </article>
  `
})
export class CardComponent {}

// Użycie
<app-card>
  <h2 card-header>Profil Samuraja</h2>

  <p>Treść główna karty - opis samuraja...</p>
  <img src="samurai.jpg" alt="Samuraj">

  <div card-footer>
    <button>Edytuj</button>
    <button>Usuń</button>
  </div>
</app-card>

Conditional Content with @if

@Component({
  selector: 'app-expandable',
  template: `
    <div class="header" (click)="toggle()">
      <ng-content select="[header]"></ng-content>
      <span>{{ isExpanded() ? '▼' : '▶' }}</span>
    </div>

    @if (isExpanded()) {
      <div class="content">
        <ng-content></ng-content>
      </div>
    }
  `
})
export class ExpandableComponent {
  isExpanded = signal(false);

  toggle(): void {
    this.isExpanded.update(v => !v);
  }
}

ContentChild i ContentChildren

@Component({
  selector: 'app-tabs',
  template: `
    <div class="tab-headers">
      @for (tab of tabs(); track tab.title) {
        <button
          [class.active]="tab === activeTab()"
          (click)="selectTab(tab)">
          {{ tab.title }}
        </button>
      }
    </div>
    <div class="tab-content">
      <ng-content></ng-content>
    </div>
  `
})
export class TabsComponent implements AfterContentInit {
  @ContentChildren(TabComponent) tabsList!: QueryList<TabComponent>;

  tabs = signal<TabComponent[]>([]);
  activeTab = signal<TabComponent | null>(null);

  ngAfterContentInit(): void {
    this.tabs.set(this.tabsList.toArray());
    if (this.tabs().length > 0) {
      this.selectTab(this.tabs()[0]);
    }
  }

  selectTab(tab: TabComponent): void {
    this.tabs().forEach(t => t.isActive.set(false));
    tab.isActive.set(true);
    this.activeTab.set(tab);
  }
}

@Component({
  selector: 'app-tab',
  template: `
    @if (isActive()) {
      <ng-content></ng-content>
    }
  `
})
export class TabComponent {
  @Input() title = '';
  isActive = signal(false);
}
Kod do tej lekcji: src/app/app.component.ts
import { Component, signal, contentChildren, AfterContentInit, input, TemplateRef, ViewContainerRef, Directive, inject } from '@angular/core';
import { CommonModule } from '@angular/common';

// Tab Component
@Component({
  selector: 'app-tab',
  standalone: true,
  template: `
    @if (isActive()) {
      <ng-content></ng-content>
    }
  `
})
export class TabComponent {
  title = input.required<string>();
  isActive = signal(false);
}

// Tabs Container Component
@Component({
  selector: 'app-tabs',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="tabs-container">
      <div class="tab-headers">
        @for (tab of tabs(); track $index) {
          <button
            class="tab-header"
            [class.active]="tab.isActive()"
            (click)="selectTab(tab)"
          >
            {{ tab.title() }}
          </button>
        }
      </div>
      <div class="tab-content">
        <ng-content></ng-content>
      </div>
    </div>
  `,
  styles: [`
    .tabs-container {
      border: 2px solid #e94560;
      border-radius: 10px;
      overflow: hidden;
    }
    .tab-headers {
      display: flex;
      background: rgba(0,0,0,0.3);
    }
    .tab-header {
      flex: 1;
      padding: 12px;
      background: transparent;
      border: none;
      color: #888;
      cursor: pointer;
      transition: all 0.3s;
    }
    .tab-header:hover {
      background: rgba(233, 69, 96, 0.2);
    }
    .tab-header.active {
      background: #e94560;
      color: white;
    }
    .tab-content {
      padding: 20px;
    }
  `]
})
export class TabsComponent implements AfterContentInit {
  tabsList = contentChildren(TabComponent);
  tabs = signal<TabComponent[]>([]);

  ngAfterContentInit(): void {
    this.tabs.set(this.tabsList().slice());
    if (this.tabs().length > 0) {
      this.selectTab(this.tabs()[0]);
    }
  }

  selectTab(selectedTab: TabComponent): void {
    this.tabs().forEach(tab => tab.isActive.set(false));
    selectedTab.isActive.set(true);
  }
}

// Card Component with Content Projection
@Component({
  selector: 'app-card',
  standalone: true,
  template: `
    <article class="card">
      <header class="card-header">
        <ng-content select="[card-header]"></ng-content>
      </header>
      <main class="card-body">
        <ng-content></ng-content>
      </main>
      <footer class="card-footer">
        <ng-content select="[card-footer]"></ng-content>
      </footer>
    </article>
  `,
  styles: [`
    .card {
      background: rgba(0,0,0,0.3);
      border-radius: 10px;
      border: 1px solid #e94560;
      overflow: hidden;
    }
    .card-header {
      background: rgba(233, 69, 96, 0.2);
      padding: 15px;
      border-bottom: 1px solid #e94560;
    }
    .card-body {
      padding: 20px;
    }
    .card-footer {
      background: rgba(0,0,0,0.2);
      padding: 15px;
      border-top: 1px solid rgba(233, 69, 96, 0.3);
    }
  `]
})
export class CardComponent {}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, TabsComponent, TabComponent, CardComponent],
  template: `
    <div class="mastery-dojo">
      <h1>Mistrzostwo Miecza - Content Projection</h1>

      <section>
        <h2>Tabs z ContentChildren</h2>

        <app-tabs>
          <app-tab title="Profil Samuraja">
            <h3>Miyamoto Musashi</h3>
            <p>Legendarny samuraj i mistrz miecza, autor "Księgi Pięciu Kręgów".</p>
            <p>Styl walki: Niten Ichi-ryū (dwa miecze)</p>
          </app-tab>
          <app-tab title="Umiejętności">
            <h3>Umiejętności bojowe</h3>
            <ul>
              <li>Miecz: ████████░░ 80%</li>
              <li>Strategia: ██████████ 100%</li>
              <li>Medytacja: ███████░░░ 70%</li>
            </ul>
          </app-tab>
          <app-tab title="Ekwipunek">
            <h3>Arsenał</h3>
            <ul>
              <li>Katana - "Musashi"</li>
              <li>Wakizashi - "Kojiro"</li>
              <li>Bokken (drewniany miecz)</li>
            </ul>
          </app-tab>
        </app-tabs>
      </section>

      <section>
        <h2>Multi-slot Content Projection</h2>

        <div class="cards-grid">
          <app-card>
            <h3 card-header>Katana</h3>
            <p>Tradycyjny japoński miecz o zakrzywionej klindze.</p>
            <p>Długość: 60-80 cm</p>
            <div card-footer>
              <button>Wybierz</button>
              <span>+50 obrażeń</span>
            </div>
          </app-card>

          <app-card>
            <h3 card-header>Yumi (Łuk)</h3>
            <p>Asymetryczny łuk japoński używany przez samurajów.</p>
            <p>Zasięg: 200m</p>
            <div card-footer>
              <button>Wybierz</button>
              <span>+30 zasięgu</span>
            </div>
          </app-card>

          <app-card>
            <h3 card-header>Zbroja</h3>
            <p>Tradycyjna zbroja samurajska (yoroi).</p>
            <p>Ochrona: wysoka</p>
            <div card-footer>
              <button>Wybierz</button>
              <span>+100 obrony</span>
            </div>
          </app-card>
        </div>
      </section>

      <section>
        <h2>Kod</h2>
        <pre><code>{{ codeExample }}</code></pre>
      </section>
    </div>
  `,
  styles: [`
    .mastery-dojo {
      font-family: 'Segoe UI', sans-serif;
      padding: 20px;
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      min-height: 100vh;
      color: #eee;
    }

    h1 {
      text-align: center;
      color: #e94560;
    }

    h2 {
      color: #e94560;
      border-bottom: 2px solid #e94560;
      padding-bottom: 10px;
    }

    section {
      background: rgba(255,255,255,0.05);
      border-radius: 10px;
      padding: 20px;
      margin: 20px 0;
    }

    .cards-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 20px;
    }

    button {
      padding: 8px 16px;
      background: #e94560;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      margin-right: 10px;
    }

    button:hover {
      background: #ff6b6b;
    }

    pre {
      background: #0a0a15;
      padding: 15px;
      border-radius: 8px;
      overflow-x: auto;
      border-left: 4px solid #e94560;
    }

    code {
      color: #e6e6e6;
      font-family: 'Fira Code', monospace;
      font-size: 0.85em;
    }
  `]
})
export class AppComponent {
  codeExample = `// Multi-slot Content Projection
@Component({
  selector: 'app-card',
  template: \`
    <article class="card">
      <header>
        <ng-content select="[card-header]"></ng-content>
      </header>
      <main>
        <ng-content></ng-content>
      </main>
      <footer>
        <ng-content select="[card-footer]"></ng-content>
      </footer>
    </article>
  \`
})
export class CardComponent {}

// Użycie
<app-card>
  <h3 card-header>Tytuł</h3>
  <p>Treść główna karty...</p>
  <div card-footer>
    <button>Akcja</button>
  </div>
</app-card>

// ContentChildren do dynamicznego dostępu
@Component({
  selector: 'app-tabs'
})
export class TabsComponent implements AfterContentInit {
  tabsList = contentChildren(TabComponent);

  ngAfterContentInit() {
    // Dostęp do wszystkich TabComponent wewnątrz
    this.tabsList().forEach(tab => ...);
  }
}`;
}

Hasła z dokumentacji w tej lekcji

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. Do czego służy atrybut select w <ng-content>?

  2. 2. Czym jest Content Projection w Angular?

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

Zadania praktyczne w grze

  • Układanie w poziomie

    Ułóż znacznik pojedynczego slotu projekcji treści (jedna linia, od lewej):

  • Klikanie w kolejności

    Kliknij elementy w kolejności, aby zbudować otwierający znacznik slotu: <ng-content>

  • Edytor kodu

    Uzupełnij komponent karty z wieloma slotami content projection.

  • Układanie w pionie

    Uporządkuj sloty karty zgodnie z kolejnością w szablonie (od góry do dołu):

  1. Pytanieng-content select
  2. PytanieCzym jest Content Projection
  3. Ułóż w kolejnościSkładnia pojedynczego slotu
  4. Kliknij w kolejnościOtwarcie znacznika ng-content
  5. PytanieQuery treści projektowanej
  6. Zadanie z kodemPraktyka: Content Projection
  7. Ułóż w kolejnościStruktura karty z wieloma slotami

Przydatne artykuły