2017-03-02 43 views
3

我有這個簡單的成分以外的成分:爲什麼ViewContainerRef的長度,即使0它裏面

export class AppComponent implements AfterViewInit { 
    constructor(private vc: ViewContainerRef) {} 

    ngAfterViewInit(): void { 
    this.vc.lenght; // 0 
    } 

而且template

<h1>Hello {{name}}</h1> 
<green></green> 

所以在這裏我已清楚主視圖的創建​​組件ViewContainerRefAppComponent。爲什麼lenght等於0呢?

回答

1

您在AppComponent構造函數中注入的ViewContainerRef不是AppComponent子組件/視圖元素的容器。它實際上屬於父組件,因此是父組件子嵌入視圖的容器。由於父組件沒有嵌入視圖,因此其長度爲0。但是,如果父組件具有嵌入視圖,您將看到其他編號。

下面是一個例子。父AppComponent創建嵌入視圖,並使用a-comp元素,這是AComponent作爲視圖容器主元素:

@Component({ 
    ... 
    template: ` 
     <h2>Hello {{name}}</h2> 
     <ng-template #t>I am embedded view</ng-template> 
     <a-comp></a-comp> 
    ` 
}) 
export class AppComponent { 
    name = `Angular! v${VERSION.full}`; 
    @ViewChild(AComponent, {read: ViewContainerRef}) acomp; 
    @ViewChild('t', {read: TemplateRef}) t; 

    constructor() {} 

    ngOnInit() { 
     this.acomp.createEmbeddedView(this.t); 
    } 
} 

現在,如果你注入ViewContainerRefAComponent你會得到1length

export class AComponent { 
    name = 'A component'; 

    constructor(private vc: ViewContainerRef) {} 

    ngAfterViewInit() { 
     console.log(this.vc.length); // 1 
    } 
} 
相關問題