2016-12-22 14 views
2

Angular2を理解しようとしていますが、何らかの理由で@ContentChildが動作していません。私の終わりからは非常に基本的な間違いがなければなりませんが、私はそれを理解できません。どんな助けでも大歓迎です。あなただけではない兄弟Angularの@ContentChildが機能しません

のコンテンツのためにそれが動作します。この道を照会することができ

app.components.ts

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

@Component({ 
    selector: 'app-root', 
    template: ` 
    <p #boundContent>{{localCounter}}</p> 
    Verify me: <p>{{boundContent.textContent}}</p> 
     <hr> 
     <fa-contentchild></fa-contentchild> 
      `, 
    styles: [` 
     h1{color:red;} 
    `] 
}) 
export class AppComponent { 
    localCounter:number =700; 
    doShow:boolean=false; 
    title = 'angular sucks!'; 
} 

contentchild.component.ts @ContentChild()

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

@Component({ 
    selector: 'fa-contentchild', 
    template: ` 
    <p>I am from content Child: {{boundContent}}</p> 
    `, 
    styles: [] 
}) 
export class ContentchildComponent implements AfterContentInit { 

    @ContentChild('boundContent') 
    boundContent:HTMLElement; 

    constructor() { } 

    ngAfterContentInit() { 
    console.log(this.boundContent); 
    } 

} 
+0

だろう、それは常に未定義のまま。 –

+1

この回答を確認してください:http://stackoverflow.com/questions/39598072/angular-2-contentchild-is-undefined – Baahubali

答えて

1

template: ` 

    Verify me: <p>{{boundContent.textContent}}</p> 
     <hr> 
     <fa-contentchild> 
     <p #boundContent>{{localCounter}}</p> 
     </fa-contentchild> 
      `, 

別の方法は、コンソールで

template: ` 
    <p #boundContent>{{localCounter}}</p> 
    Verify me: <p>{{boundContent.textContent}}</p> 
     <hr> 
     <fa-contentchild [content]="boundContent"></fa-contentchild> 
      `, 
export class ContentchildComponent implements AfterContentInit { 

    @Input() 
    boundContent:HTMLElement; 

    constructor() { } 

    ngAfterContentInit() { 
    console.log(this.boundContent); 
    } 

} 
+0

返信いただきありがとうございます。私は簡単に@Input()メタデータ/タグを使い、結果を得ました。私は@ContentChild()でデータを取得するために遊んでいたかった –

+1

入手しました。とても有難い。 –

関連する問題