'How to access an Angular Component using its injection token?

I'm working with Angular Material Drag and Drop. Material DnD is designed to create some components on the fly during the drag sequence. For instance the visual "drag" element that follows the user's cursor around the page is called the DragPreview and is created dynamically as the drag begins.

I would like to gain direct access to components like DragPreview and Angular describes how you can use injection tokens to get access to them..

enter image description here

How do I instantiate this class?

I've tried injecting CDK_DRAG_PREVIEW into my component but it fails saying that there is no provider for the injection token...

export class MyComponent {
  constructor(private ngZone: NgZone,
              private dragDrop: DragDrop,
              private dragItemService: DragItemService,
              @Inject(CDK_DRAG_PREVIEW) private dragPreview: CdkDragPreview) {
  }
}

enter image description here

It doesn't really surprise me that this doesn't work because the drag preview doesn't exist until the drag has been initiated. So logically I wouldn't expect to be able to access it in advance of that. But I'm not really sure how to get it a different way.

Closest relation I've dealt with before: MAT_DIALOG_DATA

The only other time I've dealt with a situation like this - an Angular component that doesn't exist... until it does... is with a Material Dialog. In that case you instantiate an instance of MAT_DIALOG_DATA by injecting it into the dialog component.

export class ConfirmationDialogComponent {

  title: string
  body: string

  constructor(@Inject(MAT_DIALOG_DATA) private data: DialogData) {
    this.title = data.title
    this.body = data.body
  }

}

However in this case MAT_DIALOG_DATA is implicitly already in existence because the ConfirmationDialogComponent is instantiated by the dialog service. The DragPreview doesn't exist at the time that the parent component is initialized which is at least one reason why my code might not work.

I'm a bit stuck. I know that Angular has a way for me to get to it but I just can't understand the correct syntax to get me there.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source