指令可以在同一元素上设置另一个指令吗?

问题描述 投票:0回答:2

目的

我需要使我的对话框可拖动。它们有很多,每个都是我设置样式等的自定义指令。

问题

我想知道指令是否可以选择在该元素上应用另一个指令?

代码

我的对话框看起来或多或少像这样:

<custom-dialog-container>
    <custom-dialog-header>...</custom-dialog-header>
    <custom-dialog-content>
        ...
    </custom-dialog-content>
    <custom-button>
        ...
    </custom-button>
</custom-dialog-container>

和指令:

@Directive({
  selector: 'custom-dialog-header, [customDialogHeader]'
})
export class CustomDialogHeaderDirective {
  @HostBinding('class') class = 'custom__dialog__header';
}

并且我希望指令应用 cdk 中的 3 个可拖动指令,如 this answear:

<h1 mat-dialog-title 
   cdkDrag
   cdkDragRootElement=".cdk-overlay-pane" 
   cdkDragHandle>
     Hi {{data.name}}
</h1>

是否可以使用自定义指令来做到这一点?预先感谢您的帮助。

angular angular-directive angular-cdk
2个回答
0
投票

正如@TotallyNewb所建议的,在发布这个问题时,可能没有一个选项可以通过其他指令将指令设置为html元素,但是我想出了针对我的具体问题的解决方案。这是代码,以防有人遇到类似的情况。如果您有改进的想法,请随时更新此代码。

import { DragDrop } from '@angular/cdk/drag-drop';
import { Directive, ElementRef, HostBinding } from '@angular/core';

@Directive({
  selector: 'custom-dialog-header, [customDialogHeader]'
})
export class CustomDialogHeaderDirective {
  @HostBinding('class') class = 'dialog__header';

  constructor(
    element: ElementRef<HTMLElement>,
    dragDrop: DragDrop
  ){
    let availablePanes = document.getElementsByClassName('cdk-overlay-pane');
    let latestPane = availablePanes.item(availablePanes.length - 1);
    let dragRef = dragDrop.createDrag(element);
    dragRef.withRootElement(latestPane as HTMLElement);
  }
}

0
投票

Angular 支持使用其指令组合 API 从指令中添加指令。它记录在此处:将指令添加到另一个指令

来自文档:

@Directive({...})
export class Menu { }

@Directive({...})
export class Tooltip { }

// MenuWithTooltip can compose behaviors from multiple other directives
@Directive({
  standalone: true,
  hostDirectives: [Tooltip, Menu],
})
export class MenuWithTooltip { }

// CustomWidget can apply the already-composed behaviors from MenuWithTooltip
@Directive({
  standalone: true,
  hostDirectives: [MenuWithTooltip],
})
export class SpecializedMenuWithTooltip { }
© www.soinside.com 2019 - 2024. All rights reserved.