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

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

问题描述

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

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

我想做这样的事情:

<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 装饰器.

You need to leverage the @ContentChild decorator for this.

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

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

编辑

我对您的问题进行了更多调查,由于您没有根内部 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=预览

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

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

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