Angular course · Module 14: Advanced Patterns

Advanced Patterns - The Summit of Mount Fuji

2 min read ·
In this lesson4

At the summit of Mount Fuji 富士山 - the sacred mountain of Japan - you will learn the highest techniques of swordsmanship. This is the ultimate trial before earning the title of Angular master!

Content Projection (ng-content)

Content Projection is like the technique of passing a sword to the next successor - it allows components to accept arbitrary content:

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

// Usage
<app-panel>
  <p>Any content</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 {}

// Usage
<app-card>
  <h2 card-header>Samurai Profile</h2>

  <p>Main card content - samurai description...</p>
  <img src="samurai.jpg" alt="Samurai">

  <div card-footer>
    <button>Edit</button>
    <button>Delete</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 and 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);
}
Code for this lesson: 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>Sword Mastery - Content Projection</h1>

      <section>
        <h2>Tabs with ContentChildren</h2>

        <app-tabs>
          <app-tab title="Samurai Profile">
            <h3>Miyamoto Musashi</h3>
            <p>Legendary samurai and sword master, author of "The Book of Five Rings".</p>
            <p>Fighting style: Niten Ichi-ryū (two swords)</p>
          </app-tab>
          <app-tab title="Skills">
            <h3>Combat skills</h3>
            <ul>
              <li>Sword: ████████░░ 80%</li>
              <li>Strategia: ██████████ 100%</li>
              <li>Meditation: ███████░░░ 70%</li>
            </ul>
          </app-tab>
          <app-tab title="Equipment">
            <h3>Arsenal</h3>
            <ul>
              <li>Katana - "Musashi"</li>
              <li>Wakizashi - "Kojiro"</li>
              <li>Bokken (wooden sword)</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>Traditional Japanese sword with a curved blade.</p>
            <p>Length: 60-80 cm</p>
            <div card-footer>
              <button>Select</button>
              <span>+50 damage</span>
            </div>
          </app-card>

          <app-card>
            <h3 card-header>Yumi (Bow)</h3>
            <p>Asymmetric Japanese bow used by samurai.</p>
            <p>Range: 200m</p>
            <div card-footer>
              <button>Select</button>
              <span>+30 range</span>
            </div>
          </app-card>

          <app-card>
            <h3 card-header>Armor</h3>
            <p>Traditional samurai armor (yoroi).</p>
            <p>Protection: high</p>
            <div card-footer>
              <button>Select</button>
              <span>+100 defense</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 {}

// Usage
<app-card>
  <h3 card-header>Title</h3>
  <p>Main card content...</p>
  <div card-footer>
    <button>Akcja</button>
  </div>
</app-card>

// ContentChildren for dynamic access
@Component({
  selector: 'app-tabs'
})
export class TabsComponent implements AfterContentInit {
  tabsList = contentChildren(TabComponent);

  ngAfterContentInit() {
    // Access to all TabComponent inside
    this.tabsList().forEach(tab => ...);
  }
}`;
}

Docs entries used in this lesson

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. 1. What is the select attribute on <ng-content> used for?

  2. 2. What is Content Projection in Angular?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the tag for a single content projection slot (one line, left to right):

  • Click in order

    Click the elements in order to build the opening slot tag: <ng-content>

  • Code editor

    Complete the card component with multiple content projection slots.

  • Vertical ordering

    Order the card slots to match their order in the template (top to bottom):

  1. Questionng-content select
  2. QuestionWhat is Content Projection
  3. Put in orderSingle slot syntax
  4. Click in orderOpening the ng-content tag
  5. QuestionQuerying projected content
  6. Coding taskPractice: Content Projection
  7. Put in orderStructure of a multi-slot card

Useful articles