【问题标题】:How to get html template of an Angular 2 Component?如何获取 Angular 2 组件的 html 模板?
【发布时间】:2016-11-22 21:17:21
【问题描述】:

我有一个简单的 angular 2 组件:

@Component({
  selector: 'test-text',
  template: `<p> Text </p>`
})
export class TestComponent {
  constructor() {}      
  getHtmlContent() {return;} //This should return '<p> Text </p>' as a string
}

我可以返回我的组件的 html 内容的最简单方法是什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用ElementRef。例如

    import { Component, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'test-text',
      template: `<p> Text </p>`
    })
    export class TestComponent {
      elRef: ElementRef
    
      constructor(elRef: ElementRef) {
        this.elRef = elRef;
      }      
    
      getHtmlContent() {
        //This will return '<p> Text </p>' as a string
        return this.elRef.nativeElement.innerHTML;
      }
    }
    

    【讨论】:

    • 这为您提供了 DOM 翻译的 html,它排除了所有绑定。它没有给你实际的component.template
    • @allenhwkim 这个答案显示了如何获取 component.template:stackoverflow.com/questions/45497561/…
    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 2017-03-15
    • 2019-12-27
    • 2016-04-29
    • 2018-01-11
    • 2017-11-23
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多