简体   繁体   English

在 Angular 中用 styles 获取 HTML 内容

[英]Get HTML content with styles in Angular

I have an application created using Angular.我有一个使用 Angular 创建的应用程序。 I need to get html of template of some big component but with styles that used there for classes.我需要获取一些大型组件的模板html ,但使用 styles 用于类。 How can I do that in angular?我该如何在 angular 中做到这一点? Currently I'm trying to achieve this with getting innerHTML :目前我正在尝试通过获取innerHTML来实现这一目标:

const myTemplate = document.getElementById("someWrapperId");
const content = myContent.innerHTML;

It doesn't return styled html.它不返回样式 html。 I also tried with setting encapsulation: ViewEncapsulation.None - it also doesn't help in my case.我还尝试设置encapsulation: ViewEncapsulation.None - 它对我的情况也没有帮助。 Styles are set in component.css file and not inline. Styles 在 component.css 文件中设置,而不是内联。

Hi I think you can use @ViewChild and ElementRef to get the HTML content style.嗨,我认为您可以使用@ViewChildElementRef来获取 HTML 内容样式。 I have a sample code below =>我在下面有一个示例代码=>
HTML: HTML:

<div  #infoDiv class='col-md-2' style='color: blue;width:152px'>INFO DIV</div>
<br>
Your Color:: {{styleColor}}
<br>
Your Width:: {{styleWidth}}

TS: TS:

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  styleColor:any='';
  styleWidth:any='';
  @ViewChild('infoDiv') infoDivRef: ElementRef;
  ngAfterViewInit(): void {
    if (this.infoDivRef.nativeElement) {
      console.log(this.infoDivRef.nativeElement.style.color);
      this.styleColor=this.infoDivRef.nativeElement.style.color;
       this.styleWidth=this.infoDivRef.nativeElement.style.width;
    }
  }
}

NOTE: Code is also available in stackblitz.注意:代码也可以在 stackblitz 中找到。 Please check the LINK DEMO link .请检查 LINK DEMO 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM