2016-09-18 41 views
6

Angular2 tutorial中,通過將詳細組件添加到@NgModule來引入詳細組件。如何在Angular2中聲明嵌套的組件

相反,我想通過以某種方式導入它的外部組件(AppComponent)添加它,以便只有外部組件引用內部組件。

我不知道該怎麼做。舊示例涉及directives屬性,但directives不再存在於類型ComponentMetadtaType中。所以這不起作用

import { HeroDetailComponent } from './hero-detail.component'; 

@Component({ 
    selector: 'my-app', 
    [..] 
    directives: [HeroDetailComponent] 
}) 

回答

4

您必須添加指令和組件到模塊的declarations: []
如果您只想讓一個組件能夠使用某個組件,請創建一個僅由這兩個組件組成的模塊。

@NgModule({ 
    imports: [BrowserModule], 
    declarations: [AppComponent, FooComponent, BarDirective], 
    ... 
}) 
+0

也許你是對的,但你基本上說,我想要做的是不可能做以我想要的方式? –

+0

我解釋了「以某種方式導入它」的樣子。在Angular2 final中,您需要使用模塊,並且這是使另一個組件知道一個組件,指令或管道的唯一方法。 –

+0

@KlasMellbourn這不完全是他在說什麼。確實,你不能在另一個組件中聲明一個組件。所以聲明應該移到一個外部模塊中,這個模塊仍然可以,因爲其他模塊/組件不會知道這個外部模塊,它與您的舊外部組件聲明完全一樣。 – tibbus

0

你應該聲明聲明元,如下圖所示,

import { HeroDetailComponent } from './hero-detail.component'; 
@NgModule({ 
    imports:  [ BrowserModule ], 
    declarations: [ AppComponent,HeroDetailComponent], //<----here 
    providers: [], 
    bootstrap: [ AppComponent ] 
}) 
+2

這不是他們想要做的事情。我想聲明性地導入使用內部組件的外部組件中的內部組件。 '@ NgModule'聲明沒有說明什麼在使用什麼。但也許我想要的是不可能的。 –