2016-04-11 7 views
17

コンポーネントクラス自体からコンポーネントの「コンテンツ」にアクセスするにはどうすればよいですか?部品内の角2アクセスNGコンテンツ

私はこのような何かをしたいと思います:

<upper>my text to transform to upper case</upper> 

は、どのように私は私のコンポーネント内のコンテンツまたは上のタグを取得することができ、私は属性の@Inputを使用するように?

@Component({ 
    selector: 'upper', 
    template: `<ng-content></ng-content>` 
}) 
export class UpperComponent { 
    @Input 
    content: String; 
} 

PS:私は、これは一例に過ぎず、大文字変換用のパイプを使用することができます知って、私は上のコンポーネントを作成する必要はありません、ただ部品とから、コンポーネントのコンテンツにアクセスする方法を知っていますクラス。

+0

HTML文字列または特定のコンポーネントへの参照をしますか? –

答えて

5

デコレータ@ContentChildを利用する必要があります。

@Component({ 
    selector: 'upper', 
    template: `<ng-content></ng-content>` 
}) 
export class UpperComponent { 
    @Input 
    content: String; 

    @ContentChild(...) 
    element: any; 
} 

編集

私はもう少しあなたの問題を調査しており、ルート内側のDOM要素を持っていないので、それはここ@ContentChildを使用することはできません。

DOMを直接活用する必要があります。ここでは実用的なソリューションは、次のとおりです。

@Component({ 
    selector: 'upper', 
    template: `<ng-content></ng-content>` 
}) 
export class UpperComponent { 
    constructor(private elt:ElementRef, private renderer:Renderer) { 
    } 

    ngAfterViewInit() { 
    var textNode = this.elt.nativeElement.childNodes[0]; 
    var textInput = textNode.nodeValue; 
    this.renderer.setText(textNode, textInput.toUpperCase()); 
    } 
} 

は、詳細については、このplunkrを参照してください:https://plnkr.co/edit/KBxWOnyvLovboGWDGfat?p=preview

24

あなたがトランスクルードコンテンツのコンポーネントへの参照を取得したい場合は、あなたが使用することができます。

@Component({ 
    selector: 'upper', 
    template: `<ng-content></ng-content>` 
}) 
export class UpperComponent { 
    @ContentChild(SomeComponent) content: SomeComponent; 
} 

<ng-content>をラップすると、

のようなコンテンツにアクセスできます
+0

私はそれをラップすれば、\ @ContentChildではなく\ @ViewChildを使ってアクセスする必要がありますか? –

+0

ヒントをありがとう。 –