簡體   English   中英

在 Angular 中用 styles 獲取 HTML 內容

[英]Get HTML content with styles in Angular

我有一個使用 Angular 創建的應用程序。 我需要獲取一些大型組件的模板html ,但使用 styles 用於類。 我該如何在 angular 中做到這一點? 目前我正在嘗試通過獲取innerHTML來實現這一目標:

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

它不返回樣式 html。 我還嘗試設置encapsulation: ViewEncapsulation.None - 它對我的情況也沒有幫助。 Styles 在 component.css 文件中設置,而不是內聯。

嗨,我認為您可以使用@ViewChildElementRef來獲取 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:

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;
    }
  }
}

注意:代碼也可以在 stackblitz 中找到。 請檢查 LINK DEMO 鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM