2017-03-27 40 views
3

我正在做一個帶注入的Angular 2演示,並且得到一個錯誤,我的CustomDirective不能用作入口元素。指令不能用作Angular 2中的入口組件

所以,我NgModule

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; 
import AppComponent from './app.component'; 
import {NgModule} from "@angular/core"; 

@NgModule({ 
    declarations: [AppComponent], 
    bootstrap:[AppComponent] 
}) 
export class AppModule{} 



const platform = platformBrowserDynamic(); 
platform.bootstrapModule(AppModule); 

AppComponent:

import {Component} from '@angular/core'; 
import {TIMER_DIRECTIVES} from './timer/timer'; 
import {TASK_DIRECTIVES} from './tasks/tasks'; 
import {SHARED_PROVIDERS} from './shared/shared'; 


@Component({ 
    selector: 'tomato-app', 
    entryComponents: [TIMER_DIRECTIVES,TASK_DIRECTIVES], 
    providers: [SHARED_PROVIDERS], 
    template: ` 
     <nav class="navbar navbar-default navbar-static-top"> 
      <div class="container"> 
       <div class="navbar-header"> 
        <strong class="navbar-brand">Tomato App</strong> 
       </div> 
      </div> 
     </nav> 
     <tomato-timer-widget></tomato-timer-widget> 
     <tomato-tasks></tomato-tasks>` 
}) 
export default class AppComponent{} 

而且自定義指令本身:

import {Task} from '../shared/shared' 
import {Input, HostListener, Directive} from '@angular/core'; 


@Directive({ 
    selector: '[task]' 
}) 
export default class TaskTooltipDirective { 
    private defaultTooltipText: string; 
    @Input() task: Task; 
    @Input() taskTooltip: any; 

    @HostListener('mouseover') 
    onMouseOver() { 
     if (!this.defaultTooltipText && this.taskTooltip) { 
      this.defaultTooltipText = this.taskTooltip.innerText; 
     } 
     this.taskTooltip.innerText = this.task.name; 
    } 

    @HostListener('mouseout') 
    onMouseOut() { 
     if (this.taskTooltip) { 
      this.taskTooltip.innerText = this.defaultTooltipText; 
     } 
    } 
} 

的問題是,我在AppComponent使用entryComponents不正確。我如何需要鏈接自定義指令?

+0

在根NgModule中,嘗試添加'entryComponents:[AppComponent]'。 文檔說沒有必要將AppComponent添加到entryComponents,但它不會損害您的代碼只是額外的冗餘 –

+1

此問題是否已解決? – echonax

+0

不幸的是不行 –

回答

3

entryComponents:即動態插入此組件

How do I need to link a custom directive?NgModule水平把你的所有指令,管件,部件在declarations陣列的視圖組件列表:

@NgModule({ 
    declarations: [AppComponent, TIMER_DIRECTIVES, TASK_DIRECTIVES], 
    bootstrap:[AppComponent] 
}) 
export class AppModule{} 

需要注意的是,如果您聲明providerComponent級別:

@Component({ 
    selector: 'tomato-app', 
    providers: [SHARED_PROVIDERS], 
    //... 
}) 

它將爲此組件的所有實例創建新實例。換句話說,如果你有兩個不同的組件,其中2個聲明爲providers: [SHARED_PROVIDERS],那麼2個組件的SHARED_PROVIDERS是不同的。您需要在NgModule級別聲明在此NgModule的所有組件中使用相同的實例。

@NgModule({ 
    declarations: [AppComponent, TIMER_DIRECTIVES, TASK_DIRECTIVES], 
    providers: [SHARED_PROVIDERS], 
    entryComponents: [TIMER_DIRECTIVES, TASK_DIRECTIVES], 
    bootstrap:[AppComponent] 
}) 
export class AppModule{} 
+0

仍然沒有運氣 –

+0

我已經更新了答案,請添加一個數組'entryComponents'到NgModule –