角度2访问组件内的ng-content [英] angular 2 access ng-content within component

查看:129
本文介绍了角度2访问组件内的ng-content的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从组件类本身中访问组件的内容

How can I access the "content" of a component from within the component class itself?

我想做类似的事情这个:

I would like to do something like this:

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

如何获取组件中的内容或上标签,就像我使用 @Input 属性?

How can I get the content or the upper tag within my component like I would use @Input for attributes?

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

PS:我知道我可以使用管道进行大写转换,这是只是一个例子,我不想创建一个上层组件,只知道如何从组件类访问组件的内容。

PS: I know I could use pipes for the upper case transformation, this is only an example, I don't want to create an upper component, just know how to access the component's content from with the component class.

推荐答案

你需要利用 @ContentChild 装饰器。

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

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

修改

我调查了你的问题,因为你没有root内部DOM元素,所以不能在这里使用 @ContentChild

I investigated a bit more your issue and it's not possible to use @ContentChild here since you don't have a root inner DOM element.

您需要直接利用DOM。这是一个有效的解决方案:

You need to leverage the DOM directly. Here is a working solution:

@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

See this plunkr for more details: https://plnkr.co/edit/KBxWOnyvLovboGWDGfat?p=preview

这篇关于角度2访问组件内的ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆