2017-08-30 48 views
0

答案得到基類實例:角2 - 不能與ViewChild也不ContentChild

  • 不使用EXPORTAS

  • 使用@ViewChild( '爲myContent')爲myContent;獲取父類

  • 如果視圖被初始化它只會工作的實例,所以最好使用ngAfterViewInit


這涉及繼承!

base class (component) 
    | 
inherited class (component) 

我有EXPORTAS導出的基類組分

@Component({ 
    selector: 'my-content', 
    exportAs: 'myContent', 
    ... 
}) 

繼承的類組分在繼承的使用其自己的模板

<my-content #myContent> 
    ... 

基類模板 一個參考組件的代碼我嘗試獲取其實例

@ViewChild('myContent') myContent; 

@ContentChild('myContent') myContent; 

有人說這應該工作,但爲myContent常是不確定的

我該如何解決這個問題?

感謝

+0

你能在Plunker重現? –

回答

1

爲了讓你可以直接使用組件類的父模板中的子組件的實例,無任何引用,像這樣

@ViewChild(MyComponentClass) myContent; 

MyComponentClass是的導出名稱子組件類。

作爲一個側面說明,請確保您referenceing的myComponent變量後的意見已檢查/初始化(使用ngAfterViewInit),而不是ngOnInit,因爲,在初始階段,就不會被創建子組件。

這裏有一個工作plunkr:

https://plnkr.co/edit/Q53I4EIDOL0ZrUEo2jRN?p=preview

+0

這是相反的方式,我想調用父子功能 – ninja

+0

我試着用ngAfterViewInit而不是ngOnInit,但仍然參考undefined – ninja

+0

https://plnkr.co/edit/jjN9An8G2QKzqFqk3dnp?p=preview – ninja

0

@ViewChild(MyParentComponent) myParent: MyParentComponent

可以將背景父組件一樣this.myParent

plunker:

import { Component, ViewChild } from '@angular/core'; 

@Component({...}) 

export class InheritedComponent extends BaseClassComponent { 

    @ViewChild(BaseClassComponent) myBaseclass: BaseClassComponent; 

    doSomeOperations() 
    { 
     this.myBaseclass.toggle(); 
     console.log(this.visible); 
    } 

} 
+0

那麼爲什麼調用變量myChild?它應該是myParent或其他東西。我試過你的解決方案,它不起作用 – ninja

+0

仍然在undefined的參考? – k11k2

+0

https://plnkr.co/edit/jjN9An8G2QKzqFqk3dnp?p=preview – ninja