2017-12-27 1138 views
3

我有以下查詢。 Is always the root component in Angular Component tree the bootstrap one?除了bootstraps之外,是否還有其他組件可能成爲根組件?根vs自舉組件

到目前爲止,我的理解是有一個組件樹(不管多少模塊有)和引導模塊引導組件是上述樹的根。 我正確與否?

constructor(private app: ApplicationRef) { 
    let element = this.app.components[0]; 
    console.log(element); 
} 

是否上面的代碼登錄的根組件?我認爲this.app.components 將包括組件樹的所有組件,但它不包含。 有沒有什麼辦法讓它們以編程方式?

+0

這是被自舉模塊,而不是部件,不是嗎?我嘗試引導我的導航模塊,爲了好玩,但它當然沒有引用核心角模塊,因此失敗了。 –

回答

3

可以存在多個引導組件樹。這就是bootstrap參數可以接收一組類而不是單個類的原因。

從角的官方文檔(https://angular.io/guide/bootstrapping#the-bootstrap-array

每個自舉組件是其自己的組件樹的基地。插入引導組件通常觸發填充該樹的級聯組件創建

我已經添加了一個小的plunkr來演示多個引導組件。 https://plnkr.co/edit/ChAl9N9O5cOcojNlKl0D?p=preview

app.ts

import {Component, NgModule, VERSION} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

@Component({ 
    selector: 'child', 
    template: ` 
    <div> 
     <h2>Child Number {{count}}</h2> 
    </div> 
    `, 
}) 
export class Child { 

    static counter: number = 1; 

    count: number; 

    constructor() { 
    this.count = Child.counter++; 
    } 
} 

@Component({ 
    selector: 'my-app-1', 
    template: ` 
    <div> 
     <h2>Component Tree 1</h2> 
     <child></child> 
    </div> 
    `, 
}) 
export class App1 { 
    constructor() { 
    } 
} 

@Component({ 
    selector: 'my-app-2', 
    template: ` 
    <div> 
     <h2>Component Tree 2</h2> 
     <child></child> 
    </div> 
    `, 
}) 
export class App2 { 
    constructor() { 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ Child, App1, App2 ], 
    bootstrap: [ App1, App2 ] 
}) 
export class AppModule {} 

的index.html

<!DOCTYPE html> 
<html> 

    <head> 
    <base href="." /> 
    <script type="text/javascript" charset="utf-8"> 
     window.AngularVersionForThisPlunker = 'latest' 
    </script> 
    <title>angular playground</title> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="https://unpkg.com/[email protected]/client/shim.min.js"></script> 
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script> 
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script> 
    <script src="https://unpkg.com/[email protected]/Reflect.js"></script> 
    <script src="https://unpkg.com/[email protected]/dist/system.js"></script> 
    <script src="config.js"></script> 
    <script> 
    System.import('app') 
     .catch(console.error.bind(console)); 
    </script> 
    </head> 

    <body> 
    <my-app-1> 
    loading... 
    </my-app-1> 
    <my-app-2> 
    loading... 
    </my-app-2> 
    </body> 

</html> 
0

不,組件可以彼此分開,不必組成分層樹。

+0

但是,如果有層次樹,我的假設是否正確? –

+0

您可以擁有許多樹,因爲根組件與其他組件相同。它只是啓動樹層次結構。它只是一個設計metter – Antoniossss

+0

你知道有什麼好的資源來閱讀更多的東西嗎?我自己沒有找到任何好的東西。 –