javascript – 组件中的角度2访问内容

前端之家收集整理的这篇文章主要介绍了javascript – 组件中的角度2访问内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从组件类本身访问组件的“内容”?

我想做这样的事情:

<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:我知道我可以使用管道进行大写转换,这只是一个例子,我不想创建一个上层组件,只需知道如何从组件类访问组件的内容.

解决方法

您需要为此使用@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

原文链接:https://www.f2er.com/js/154912.html

猜你在找的JavaScript相关文章