Home > front end >  How to access third party component inside a directive?
How to access third party component inside a directive?

Time:10-17

I am trying to apply a directive to a kendo dropdown and would like to access the host kendo dropdown component instance.

The requirement - When the user presses escape on the kendo dropdown, it closes the dropdown. This is handled by kendo. But I don't want the event to bubble up in case if the dropdown is open. I want it to bubble up only if the dropdown is closed.

The reason being, I have attached an escape event to my page. When the user hits escape I want to close the page. But currently what happens is that if the user presses escape on the dropdown, with the intent to close the dropdown it closes the panel as well.

I know I can always handle keydown event on my dropdowns and handle it manually. But what I am trying to do is create a directive which I will attach to kendo dropdown. In the directive if I could get hold of the kendo dropdown component then based on the open/close state of the dropdown I can decide whether to bubble up the event or not.

Please have a look at the sample https://stackblitz.com/edit/angular-dnw6ps?file=app/ddclose.directive.ts

  <kendo-dropdownlist appDdclose  [data]="listItems" ></kendo-dropdownlist>
export class DdcloseDirective {
  constructor(public component: DropDownListComponent) {
    console.log(this.component);
  }
}

I get the below error

ERROR
Error: StaticInjectorError(AppModule)[DdcloseDirective -> DropDownListComponent]:
StaticInjectorError(Platform: core)[DdcloseDirective -> DropDownListComponent]:
NullInjectorError: No provider for DropDownListComponent!

CodePudding user response:

Seems like your importing the wrong module. Please check the below code.

Old:

import { DropDownListComponent } from '@progress/kendo-angular-dropdowns/dist/es2015/main';

New:

import { DropDownListComponent } from '@progress/kendo-angular-dropdowns';

Code:

import { Directive, Host, Self } from '@angular/core';
import { DropDownListComponent } from '@progress/kendo-angular-dropdowns';

@Directive({
  selector: '[appDdclose]',
  providers: [
    { provide: 'DropDownListComponent', useExisting: DropDownListComponent },
  ],
})
export class DdcloseDirective {
  constructor(@Host() @Self() public component: DropDownListComponent) {
    console.log(this.component);
  }

  ngAfterViewInit() {
    console.log(this.component);
  }
}

Stackblitz

  • Related