Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1170

Can't resolve all parameters for custom directive

I created a custom directive to open a link in a new tab, when running in ng serve, it works. However, when I tried in ng build --prod, it showed this error:

ERROR in Can't resolve all parameters for OpenLinkInNewTabDirective in C:/Users/myApp/src/app/directives/open-link-in-new-tab.directive.ts: ([object Object], ?).

Here is the directive:

import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';

@Directive({ selector: '[newTab]' })
export class OpenLinkInNewTabDirective {
    constructor(
      private el: ElementRef,
      @Inject(Window) private win:Window
    ) {}

    @Input('routerLink') link: string;
    @HostListener('mousedown') onMouseEnter() {
        this.win.open(this.link || 'main/default');
    }
}

I set "emitDecoratorMetadata": true in tsconfig.json already. Thank you in advance.

Upvotes: 1

Views: 1289

Answers (1)

angularconsulting.au
angularconsulting.au

Reputation: 28279

It is known issue because Window is an typescript interface. You need to trick a compiler by creating a fake class say WindowWrapper.ts

@Injectable()
export class WindowWrapper extends Window { }
export function getWindow() { return window; }

app.module:

import { WindowWrapper, getWindow } from './WindowWrapper';

providers: [
     {provide: WindowWrapper, useFactory: getWindow}
  ],

directive:

import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
import { WindowWrapper } from './WindowWrapper';

@Directive({ 
    selector: '[newTab]'
})
export class OpenLinkInNewTabDirective {
    constructor(
      private el: ElementRef,
      @Inject(WindowWrapper) private win: Window) {}

    @Input('routerLink') link: string;
    @HostListener('mousedown') onMouseEnter() {
        this.win.open(this.link || 'main/default');
    }
}

check more details on that isse and that particular comment

Upvotes: 1

Related Questions