2

Purpose

I need to make my dialogs draggable. There are plenty of them and on each is my custom directive that sets styles etc.

Question

I wonder if there is an option for a directive to apply another directives on that element?

Code

My dialogs look more or less like this:

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

and the directive:

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

and I would like the directive to apply 3 draggable directives from cdk like in this answear:

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

Is it possible to do it using the custom directive? Thank you in advance for any help.

big_OS
  • 381
  • 7
  • 20
  • 1
    Directives are meant to be added to the markup - that's the way Angular was designed. You can try to work around it by manually adding attribute and instantiating a class of the directive, but there is not actual guarantee that all the features will work (now or in the future). – TotallyNewb May 18 '21 at 08:46
  • Does this answer your question? [How to dynamically add a directive?](https://stackoverflow.com/questions/41298168/how-to-dynamically-add-a-directive) – TotallyNewb May 18 '21 at 08:47

1 Answers1

0

As @TotallyNewb suggested, there might not be an option to set directives by other directives to html elements at the time this question was posted, but I came up with a solution to my specific problem. Here's the code in case someone comes across a similar situation. Feel free to update this code if you have an idea to improve it.

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);
  }
}
big_OS
  • 381
  • 7
  • 20