2017-07-19 98 views
1

的所有參數我完全是Angular的新手,並試圖從Angular嚮導中注入basic structural directive。這裏是我的指令:Angular 4指令錯誤:無法解析指令

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; 

@Directive({ 
    selector: '[pcDropdown]' 
}) 
export class DropdownDirective { 
    private hasView = false; 

    constructor(
    private templateRef: TemplateRef<any>, 
    private viewContainer: ViewContainerRef, 
    private items 
) { } 

    @Input() set pcDropdown(condition: boolean) { 
    if (!condition && !this.hasView) { 
     this.viewContainer.createEmbeddedView(this.templateRef); 
     this.hasView = true; 
    } else if (condition && this.hasView) { 
     this.viewContainer.clear(); 
     this.hasView = false; 
    } 
    } 
} 

我試圖把它注射在我TradeModule

import { NgModule } from '@angular/core'; 
import { CommonModule } from '@angular/common'; 
import { SharedModule } from '../shared/shared.module'; 
import { TradeComponent } from './trade.component'; 
import { DropdownDirective } from '../dropdown.directive/dropdown.directive'; 

@NgModule({ 
    imports: [ 
    CommonModule, 
    SharedModule 
    ], 
    declarations: [TradeComponent, DropdownDirective], 
    exports: [DropdownDirective] 
}) 
export class TradeModule { } 

在我TradeComponent的模板中使用HTML的以下部分:

... 
<p *pcDropdown="true"> 
    TEST 
</p> 
... 

但我得到的錯誤:

Uncaught Error: Can't resolve all parameters for DropdownDirective: ([object Object], [object Object], ?).

Webstorm也基本我@Directive裝飾,說以下內容:

Angular: Can't resolve all parameters for DropdownDirective in /home/commercialsuicide/Desktop/my-app/src/client/app/dropdown.directive/dropdown.directive.ts: ([object Object], [object Object], ?)

enter image description here

它還說,我pcDropdown輸入未使用:

enter image description here

需要說的,那我已經看到this answeremitDecoratorMetadata已經設置爲truetsconfig.json

請點,我拼寫錯誤或忘記包括在我的代碼中的東西。

非常感謝

回答

2

private items缺少一個類型參數。如果Angular無法解析提供者的所有參數,則不能創建組件實例。
解析爲供應商僅適用於參數類型和@Inject(...)註釋。

如果您不想要注入items,請刪除該參數。你不需要自己創建一個組件實例來明確地傳遞參數。

+0

嗯,這個解決方案是非常基礎的。非常感謝你的幫助! –

+1

提示:錯誤信息用'?'指出哪個參數導致錯誤'DropdownDirective:([object Object],[object Object],?)。'。很高興聽到這個解決它已經爲你:) –

0

我剛剛把我的情況留在了這裏,因爲我的請求發現了這個問題。

我有註解@HostListener和onResize方法。 @HostListener應該在之前並且接近相關的方法。像

@HostListener("window:resize", ["$event"]) 
onResize(event) { 
    // some code 
} 

我得到這個錯誤,當調用另一個方法之前移動註釋。像

@HostListener("window:resize", ["$event"]) 
getSomeObjects (args:any = {}) { 
    // some code 
} 

onResize(event) { 
    // some code 
} 

希望,這將有助於某人!