2016-04-11 42 views
17

如何从组件类本身访问组件的“内容”?angular 2访问组件内的ng-content

我愿做这样的事情:

<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; 
} 

编辑

我研究多一点您的问题,这是不可能的使用@ContentChild在这里,因为你没有根内DOM元素。

您需要直接利用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

如果你想要去的transcluded内容的组件的引用,你可以使用:

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

如果你换行<ng-content>那么你可以访问transcluded内容,如

@Component({ 
    selector: 'upper', 
    template: ` 
    <div #contentWrapper> 
    <ng-content></ng-content> 
    </div>` 
}) 
export class UpperComponent { 
    @ViewChild('contentWrapper') content: ElementRef; 

    ngAfterViewInit() { 
     console.debug(this.content.nativeElement); 
    } 
} 
+0

如果我包装它,我应该使用\ @ViewChild访问它,而不是\ @ContentChild? –

+0

对。感谢提示。 –