2017-05-03 155 views
2

比方說,我們有一個叫做TopComponent組件與這樣的一個模板:角訪問內部組件

<ng-template #top> 
    <inner-selector #inner></inner-selector> 
</ng-template> 

它的代碼很簡單:

//... imports ... 

@Component({ 
    // selector, styles etc 
}) 
export class TopComponent implements AfterViewInit { 

    @ViewChild('top') topComp : NgbModal; 
    // NgbModal is a type provided by some 3rd-party library 
    // I can't modify it 

    ngAfterViewInit() { 
    // let's access the #inner component from here 
    } 
} 

我可以訪問#top組件使用此代碼:

@ViewChild('top') topComponent: TopComponent; 

我該如何訪問#inner組件來自同一類?

我試過使用@ContentChild('inner'),但仍然得到undefined

PS。我知道我可以創建另一個組件,使用它而不是<ng-template>,並從中訪問所有必需的孩子。但是這可以以某種方式避免嗎?

+0

它不應該是'@ViewChild( '#' 頂部)'? – Meir

+0

@Meir,你的意思是訪問'#top'組件? 沒有'#'符號就可以正常工作。 –

回答

1

使用後代@ViewChild('inner',{descendants:true})inner:InnerSelector;

這裏是填寫代碼:https://plnkr.co/edit/MtVhHuAtPXZzC7GLOidF?p=preview

@Component({ 
    selector: 'inner-selector', 
    template:'inner-selector here' 
    }) 
    export class InnerSelector { 
    myVar = 0; 
    } 

    @Component({ 
    selector: 'my-app', 
    template: ` 
     <div> 
     <ng-template #top> 
      <inner-selector #inner></inner-selector> 
     </ng-template> 

     <ng-container [ngTemplateOutlet]="top"></ng-container> 
     </div> 
    `, 
    }) 
    export class App { 
    @ViewChild('inner', {descendants: true}) inner: InnerSelector; 
    constructor() { 
     this.name = `Angular! v${VERSION.full}` 
    } 
    ngAfterViewInit() { 
     console.log(this.inner); 
    } 
    } 
+0

感謝您的回答,朱莉婭。但它說'後代'不能使用。只允許'read:any'。我需要一個專門的圖書館嗎? –

+0

什麼版本的角-2或4? –

+0

我使用Angular版本4.1 –