【问题标题】:Can directive set another directives on the same element?指令可以在同一个元素上设置另一个指令吗?
【发布时间】:2021-08-07 11:36:33
【问题描述】:

目的

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

问题

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

代码

我的对话框或多或少是这样的:

<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 的设计方式。您可以尝试通过手动添加属性并实例化指令的类来解决它,但实际上并不能保证所有功能都可以正常工作(现在或将来)。
  • 这能回答你的问题吗? How to dynamically add a directive?

标签: angular angular-directive angular-cdk


【解决方案1】:

正如@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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2016-09-26
    • 2019-12-10
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多