angular-directives

angular-directives

热门

在 Angular v20+ 中创建自定义指令,用于 DOM 操作和行为扩展。适用于属性指令(修改元素行为/外观)、结构指令(门户/覆盖层)和宿主指令(组合)。触发场景:创建可复用的 DOM 行为、扩展元素功能、跨组件组合行为。注意:控制流请使用原生 @if/@for/@switch,不要使用自定义结构指令。

596Star
70Fork
更新于 2026/3/23
SKILL.md
readonly只读
name
angular-directives
description

在 Angular v20+ 中创建自定义指令,用于 DOM 操作和行为扩展。适用于属性指令(修改元素行为/外观)、结构指令(门户/覆盖层)和宿主指令(组合)。触发场景:创建可复用的 DOM 行为、扩展元素功能、跨组件组合行为。注意:控制流请使用原生 @if/@for/@switch,不要使用自定义结构指令。

Angular 指令

在 Angular v20+ 中创建自定义指令,实现可复用的 DOM 操作和行为。

属性指令

修改元素的外观或行为:

import { Directive, input, effect, inject, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class Highlight {
  private el = inject(ElementRef<HTMLElement>);
  
  // 使用别名匹配选择器的输入
  color = input('yellow', { alias: 'appHighlight' });
  
  constructor() {
    effect(() => {
      this.el.nativeElement.style.backgroundColor = this.color();
    });
  }
}

// 使用: <p appHighlight="lightblue">高亮文本</p>
// 使用: <p appHighlight>默认黄色高亮</p>

使用 host 属性

优先使用 host 而非 @HostBinding/@HostListener

@Directive({
  selector: '[appTooltip]',
  host: {
    '(mouseenter)': 'show()',
    '(mouseleave)': 'hide()',
    '[attr.aria-describedby]': 'tooltipId',
  },
})
export class Tooltip {
  text = input.required<string>({ alias: 'appTooltip' });
  position = input<'top' | 'bottom' | 'left' | 'right'>('top');
  
  tooltipId = `tooltip-${crypto.randomUUID()}`;
  private tooltipEl: HTMLElement | null = null;
  private el = inject(ElementRef<HTMLElement>);
  
  show() {
    this.tooltipEl = document.createElement('div');
    this.tooltipEl.id = this.tooltipId;
    this.tooltipEl.className = `tooltip tooltip-${this.position()}`;
    this.tooltipEl.textContent = this.text();
    this.tooltipEl.setAttribute('role', 'tooltip');
    document.body.appendChild(this.tooltipEl);
    this.positionTooltip();
  }
  
  hide() {
    this.tooltipEl?.remove();
    this.tooltipEl = null;
  }
  
  private positionTooltip() {
    // 基于 this.position() 和 this.el 的定位逻辑
  }
}

// 使用: <button appTooltip="点击保存" position="bottom">保存</button>

类和样式操作

@Directive({
  selector: '[appButton]',
  host: {
    'class': 'btn',
    '[class.btn-primary]': 'variant() === "primary"',
    '[class.btn-secondary]': 'variant() === "secondary"',
    '[class.btn-sm]': 'size() === "small"',
    '[class.btn-lg]': 'size() === "large"',
    '[class.disabled]': 'disabled()',
    '[attr.disabled]': 'disabled() || null',
  },
})
export class Button {
  variant = input<'primary' | 'secondary'>('primary');
  size = input<'small' | 'medium' | 'large'>('medium');
  disabled = input(false, { transform: booleanAttribute });
}

// 使用: <button appButton variant="primary" size="large">点击</button>

事件处理

@Directive({
  selector: '[appClickOutside]',
  host: {
    '(document:click)': 'onDocumentClick($event)',
  },
})
export class ClickOutside {
  private el = inject(ElementRef<HTMLElement>);
  
  clickOutside = output<void>();
  
  onDocumentClick(event: MouseEvent) {
    if (!this.el.nativeElement.contains(event.target as Node)) {
      this.clickOutside.emit();
    }
  }
}

// 使用: <div appClickOutside (clickOutside)="closeMenu()">...</div>

键盘快捷键

@Directive({
  selector: '[appShortcut]',
  host: {
    '(document:keydown)': 'onKeydown($event)',
  },
})
export class Shortcut {
  key = input.required<string>({ alias: 'appShortcut' });
  ctrl = input(false, { transform: booleanAttribute });
  shift = input(false, { transform: booleanAttribute });
  alt = input(false, { transform: booleanAttribute });
  
  triggered = output<KeyboardEvent>();
  
  onKeydown(event: KeyboardEvent) {
    const keyMatch = event.key.toLowerCase() === this.key().toLowerCase();
    const ctrlMatch = this.ctrl() ? event.ctrlKey || event.metaKey : !event.ctrlKey && !event.metaKey;
    const shiftMatch = this.shift() ? event.shiftKey : !event.shiftKey;
    const altMatch = this.alt() ? event.altKey : !event.altKey;
    
    if (keyMatch && ctrlMatch && shiftMatch && altMatch) {
      event.preventDefault();
      this.triggered.emit(event);
    }
  }
}

// 使用: <button appShortcut="s" ctrl (triggered)="save()">保存 (Ctrl+S)</button>

结构指令

将结构指令用于控制流之外的 DOM 操作(门户、覆盖层、动态插入点)。条件判断和循环请使用原生 @if@for@switch

门户指令

在不同 DOM 位置渲染内容:

import { Directive, inject, TemplateRef, ViewContainerRef, OnInit, OnDestroy, input } from '@angular/core';

@Directive({
  selector: '[appPortal]',
})
export class Portal implements OnInit, OnDestroy {
  private templateRef = inject(TemplateRef<any>);
  private viewContainerRef = inject(ViewContainerRef);
  private viewRef: EmbeddedViewRef<any> | null = null;
  
  // 目标容器选择器或元素
  target = input<string | HTMLElement>('body', { alias: 'appPortal' });
  
  ngOnInit() {
    const container = this.getContainer();
    if (container) {
      this.viewRef = this.viewContainerRef.createEmbeddedView(this.templateRef);
      this.viewRef.rootNodes.forEach(node => container.appendChild(node));
    }
  }
  
  ngOnDestroy() {
    this.viewRef?.destroy();
  }
  
  private getContainer(): HTMLElement | null {
    const target = this.target();
    if (typeof target === 'string') {
      return document.querySelector(target);
    }
    return target;
  }
}

// 使用: 在 body 级别渲染模态框
// <div *appPortal="'body'">
//   <div class="modal">模态框内容</div>
// </div>

延迟渲染指令

在条件满足前推迟渲染(仅一次):

@Directive({
  selector: '[appLazyRender]',
})
export class LazyRender {
  private templateRef = inject(TemplateRef<any>);
  private viewContainer = inject(ViewContainerRef);
  private rendered = false;
  
  condition = input.required<boolean>({ alias: 'appLazyRender' });
  
  constructor() {
    effect(() => {
      // 仅在条件变为 true 时渲染一次
      if (this.condition() && !this.rendered) {
        this.viewContainer.createEmbeddedView(this.templateRef);
        this.rendered = true;
      }
    });
  }
}

// 使用: 仅在标签页首次激活时渲染重型组件
// <div *appLazyRender="activeTab() === 'reports'">
//   <app-heavy-reports />
// </div>

带上下文的模板出口

interface TemplateContext<T> {
  $implicit: T;
  item: T;
  index: number;
}

@Directive({
  selector: '[appTemplateOutlet]',
})
export class TemplateOutlet<T> {
  private viewContainer = inject(ViewContainerRef);
  private currentView: EmbeddedViewRef<TemplateContext<T>> | null = null;
  
  template = input.required<TemplateRef<TemplateContext<T>>>({ alias: 'appTemplateOutlet' });
  context = input.required<T>({ alias: 'appTemplateOutletContext' });
  index = input(0, { alias: 'appTemplateOutletIndex' });
  
  constructor() {
    effect(() => {
      const template = this.template();
      const context = this.context();
      const index = this.index();
      
      if (this.currentView) {
        this.currentView.context.$implicit = context;
        this.currentView.context.item = context;
        this.currentView.context.index = index;
        this.currentView.markForCheck();
      } else {
        this.currentView = this.viewContainer.createEmbeddedView(template, {
          $implicit: context,
          item: context,
          index,
        });
      }
    });
  }
}

// 使用: 自定义列表模板
// <ng-template #itemTemplate let-item let-i="index">
//   <div>{{ i }}: {{ item.name }}</div>
// </ng-template>
// <ng-container 
//   *appTemplateOutlet="itemTemplate; context: item; index: i"
// />

宿主指令

在组件或其他指令上组合指令:

// 可复用的行为指令
@Directive({
  selector: '[focusable]',
  host: {
    'tabindex': '0',
    '(focus)': 'onFocus()',
    '(blur)': 'onBlur()',
    '[class.focused]': 'isFocused()',
  },
})
export class Focusable {
  isFocused = signal(false);
  
  onFocus() { this.isFocused.set(true); }
  onBlur() { this.isFocused.set(false); }
}

@Directive({
  selector: '[disableable]',
  host: {
    '[class.disabled]': 'disabled()',
    '[attr.aria-disabled]': 'disabled()',
  },
})
export class Disableable {
  disabled = input(false, { transform: booleanAttribute });
}

// 使用宿主指令的组件
@Component({
  selector: 'app-custom-button',
  hostDirectives: [
    Focusable,
    {
      directive: Disableable,
      inputs: ['disabled'],
    },
  ],
  host: {
    'role': 'button',
    '(click)': 'onClick($event)',
    '(keydown.enter)': 'onClick($event)',
    '(keydown.space)': 'onClick($event)',
  },
  template: `<ng-content />`,
})
export class CustomButton {
  private disableable = inject(Disableable);
  
  clicked = output<void>();
  
  onClick(event: Event) {
    if (!this.disableable.disabled()) {
      this.clicked.emit();
    }
  }
}

// 使用: <app-custom-button disabled>点击我</app-custom-button>

暴露宿主指令的输出

@Directive({
  selector: '[hoverable]',
  host: {
    '(mouseenter)': 'onEnter()',
    '(mouseleave)': 'onLeave()',
    '[class.hovered]': 'isHovered()',
  },
})
export class Hoverable {
  isHovered = signal(false);
  
  hoverChange = output<boolean>();
  
  onEnter() {
    this.isHovered.set(true);
    this.hoverChange.emit(true);
  }
  
  onLeave() {
    this.isHovered.set(false);
    this.hoverChange.emit(false);
  }
}

@Component({
  selector: 'app-card',
  hostDirectives: [
    {
      directive: Hoverable,
      outputs: ['hoverChange'],
    },
  ],
  template: `<ng-content />`,
})
export class Card {}

// 使用: <app-card (hoverChange)="onHover($event)">...</app-card>

指令组合 API

组合多个行为:

// 基础指令
@Directive({ selector: '[withRipple]' })
export class Ripple {
  // 涟漪效果实现
}

@Directive({ selector: '[withElevation]' })
export class Elevation {
  elevation = input(2);
}

// 组合组件
@Component({
  selector: 'app-material-button',
  hostDirectives: [
    Ripple,
    {
      directive: Elevation,
      inputs: ['elevation'],
    },
    {
      directive: Disableable,
      inputs: ['disabled'],
    },
  ],
  template: `<ng-content />`,
})
export class MaterialButton {}

高级模式请参见 references/directive-patterns.md