Kurs Angular · Moduł 14: Zaawansowane wzorce

Własne Dyrektywy

2 min czytania ·
W tej lekcji3

Dyrektywy to jak tajne techniki ninja - rozszerzają możliwości elementów.

Attribute Directive

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  private el = inject(ElementRef);
  private renderer = inject(Renderer2);

  // Input z aliasem (nazwa dyrektywy)
  @Input() appHighlight = '#ffff00';
  @Input() highlightOnFocus = false;

  @HostListener('mouseenter')
  onMouseEnter(): void {
    this.setBackground(this.appHighlight);
  }

  @HostListener('mouseleave')
  onMouseLeave(): void {
    this.setBackground('');
  }

  @HostListener('focus')
  onFocus(): void {
    if (this.highlightOnFocus) {
      this.setBackground(this.appHighlight);
    }
  }

  private setBackground(color: string): void {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}

// Użycie
<p appHighlight="#ffff00">Żółte podświetlenie</p>  <!-- samo <p appHighlight> przekazałoby do inputu pusty napis zamiast wartości domyślnej -->
<p [appHighlight]="'#c41e3a'">Czerwone podświetlenie</p>
<input [appHighlight]="'#90EE90'" [highlightOnFocus]="true">

Structural Directive

@Directive({
  selector: '[appRepeat]',
  standalone: true
})
export class RepeatDirective {
  private templateRef = inject(TemplateRef<any>);
  private viewContainer = inject(ViewContainerRef);

  @Input() set appRepeat(count: number) {
    this.viewContainer.clear();

    for (let i = 0; i < count; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef, {
        $implicit: i,  // Dostępne jako let-i
        index: i,
        first: i === 0,
        last: i === count - 1
      });
    }
  }
}

// Użycie
<div *appRepeat="5; let i; let isFirst = first">
  Element {{ i }} {{ isFirst ? '(pierwszy)' : '' }}
</div>

Permission Directive

@Directive({
  selector: '[appHasPermission]',
  standalone: true
})
export class HasPermissionDirective {
  private templateRef = inject(TemplateRef<any>);
  private viewContainer = inject(ViewContainerRef);
  private authService = inject(AuthService);

  private hasView = false;

  @Input() set appHasPermission(permission: string | string[]) {
    const permissions = Array.isArray(permission) ? permission : [permission];
    const hasPermission = this.authService.hasAnyPermission(permissions);

    if (hasPermission && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (!hasPermission && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }
}

// Użycie
<button *appHasPermission="'admin'">Panel Admin</button>
<div *appHasPermission="['editor', 'admin']">Edycja treści</div>
Kod do tej lekcji: src/app/app.component.ts
import { Component, signal, Directive, ElementRef, Renderer2, inject, HostListener, input, Pipe, PipeTransform } from '@angular/core';
import { CommonModule } from '@angular/common';

// Custom Directive - Highlight
@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  private el = inject(ElementRef);
  private renderer = inject(Renderer2);

  appHighlight = input('#ffff00');

  @HostListener('mouseenter')
  onMouseEnter(): void {
    this.setBackground(this.appHighlight());
  }

  @HostListener('mouseleave')
  onMouseLeave(): void {
    this.setBackground('');
  }

  private setBackground(color: string): void {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
    this.renderer.setStyle(this.el.nativeElement, 'transition', 'background-color 0.3s');
  }
}

// Custom Pipe - Truncate
@Pipe({
  name: 'truncate',
  standalone: true
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 50, trail = '...'): string {
    if (!value) return '';
    if (value.length <= limit) return value;
    return value.substring(0, limit) + trail;
  }
}

// Custom Pipe - Relative Time
@Pipe({
  name: 'relativeTime',
  standalone: true
})
export class RelativeTimePipe implements PipeTransform {
  transform(value: Date | string | number): string {
    const date = new Date(value);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'teraz';
    if (diffMins < 60) return `${diffMins} min temu`;
    if (diffHours < 24) return `${diffHours} godz. temu`;
    if (diffDays < 7) return `${diffDays} dni temu`;

    return date.toLocaleDateString('pl-PL');
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, HighlightDirective, TruncatePipe, RelativeTimePipe],
  template: `
    <div class="advanced-dojo">
      <h1>Własne Dyrektywy i Pipes</h1>

      <section>
        <h2>Custom Directive - Highlight</h2>

        <div class="directive-demo">
          <p appHighlight>
            Najedź na mnie! (domyślny kolor: żółty)
          </p>

          <p [appHighlight]="'#e94560'">
            Najedź na mnie! (kolor: różowy)
          </p>

          <p [appHighlight]="'#2ecc71'">
            Najedź na mnie! (kolor: zielony)
          </p>
        </div>

        <pre><code>{{ directiveCode }}</code></pre>
      </section>

      <section>
        <h2>Custom Pipe - Truncate</h2>

        <div class="pipe-demo">
          <p><strong>Oryginalny tekst:</strong></p>
          <p class="original">{{ longText }}</p>

          <p><strong>Skrócony (50 znaków):</strong></p>
          <p class="truncated">{{ longText | truncate }}</p>

          <p><strong>Skrócony (30 znaków, ">>>"):</strong></p>
          <p class="truncated">{{ longText | truncate:30:'>>>' }}</p>
        </div>
      </section>

      <section>
        <h2>⏰ Custom Pipe - Relative Time</h2>

        <div class="time-demo">
          @for (event of events(); track event.id) {
            <div class="event-item">
              <span class="event-name">{{ event.name }}</span>
              <span class="event-time">{{ event.date | relativeTime }}</span>
            </div>
          }
        </div>
      </section>

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

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

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

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

    .directive-demo p {
      padding: 15px;
      margin: 10px 0;
      border-radius: 8px;
      background: rgba(0,0,0,0.3);
      cursor: pointer;
      transition: all 0.3s;
    }

    .pipe-demo .original {
      background: rgba(0,0,0,0.3);
      padding: 15px;
      border-radius: 8px;
    }

    .pipe-demo .truncated {
      background: rgba(168, 85, 247, 0.2);
      border: 1px solid #a855f7;
      padding: 15px;
      border-radius: 8px;
    }

    .time-demo {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .event-item {
      display: flex;
      justify-content: space-between;
      padding: 12px;
      background: rgba(0,0,0,0.3);
      border-radius: 8px;
      border-left: 4px solid #a855f7;
    }

    .event-name {
      font-weight: bold;
    }

    .event-time {
      color: #a855f7;
    }

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

    code {
      color: #e6e6e6;
      font-family: 'Fira Code', monospace;
      font-size: 0.85em;
    }
  `]
})
export class AppComponent {
  longText = 'Miyamoto Musashi był legendarnym japońskim szermistrza, filozofem i artystą. Napisał "Księgę Pięciu Kręgów", klasyczny tekst o strategii i sztuce walki.';

  events = signal([
    { id: 1, name: 'Trening poranny', date: new Date() },
    { id: 2, name: 'Medytacja', date: new Date(Date.now() - 30 * 60000) },
    { id: 3, name: 'Walka treningowa', date: new Date(Date.now() - 3 * 3600000) },
    { id: 4, name: 'Spotkanie z mistrzem', date: new Date(Date.now() - 2 * 86400000) },
    { id: 5, name: 'Ceremonia herbaciana', date: new Date(Date.now() - 10 * 86400000) }
  ]);

  directiveCode = `@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  private el = inject(ElementRef);
  private renderer = inject(Renderer2);

  appHighlight = input('#ffff00');

  @HostListener('mouseenter')
  onMouseEnter(): void {
    this.setBackground(this.appHighlight());
  }

  @HostListener('mouseleave')
  onMouseLeave(): void {
    this.setBackground('');
  }

  private setBackground(color: string): void {
    this.renderer.setStyle(
      this.el.nativeElement,
      'backgroundColor',
      color
    );
  }
}

// Użycie
<p appHighlight>Domyślny żółty</p>
<p [appHighlight]="'#e94560'">Różowy</p>`;

  pipeCode = `@Pipe({
  name: 'truncate',
  standalone: true
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 50, trail = '...'): string {
    if (!value) return '';
    if (value.length <= limit) return value;
    return value.substring(0, limit) + trail;
  }
}

// Użycie
{{ longText | truncate }}
{{ longText | truncate:30:'>>>' }}

@Pipe({
  name: 'relativeTime',
  standalone: true
})
export class RelativeTimePipe implements PipeTransform {
  transform(value: Date | string | number): string {
    const date = new Date(value);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);

    if (diffMins < 1) return 'teraz';
    if (diffMins < 60) return \`\${diffMins} min temu\`;
    // ...
  }
}

// Użycie
{{ event.date | relativeTime }}`;
}

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. Co potrzebujemy wstrzyknąć do stworzenia własnej structural directive?

  2. 2. Dyrektywa zmieniająca tło elementu przy najechaniu myszą (appHighlight) to przykład:

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

Zadania praktyczne w grze

  • Układanie w poziomie

    Ułóż dekorator nasłuchujący zdarzenie mouseenter na elemencie hosta (jedna linia, od lewej):

  • Edytor kodu

    Uzupełnij dyrektywę highlight zmieniającą tło przy hover.

  • Układanie w pionie

    Uporządkuj kolejne linie definicji attribute directive (od góry do dołu):

  1. PytanieStructural Directive
  2. PytanieRodzaj dyrektywy highlight
  3. Ułóż w kolejnościNasłuchiwanie zdarzeń elementu
  4. Zadanie z kodemPraktyka: Attribute Directive
  5. Ułóż w kolejnościStruktura attribute directive
  6. PytanieRenderowanie szablonu w DOM

Przydatne artykuły