Search code examples
angularangular-directiveangular-cdk

Can directive set another directives on the same element?


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.


Solution

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