import { Injectable } from '@angular/core' ; @ Injectable ( { providedIn : 'root' } ) export class StyleService { private _headElement : HTMLHeadElement ; private get headElement ( ) : HTMLHeadElement { if ( ! this . _headElement && document . getElementsByTagName ( "head" ) . length > 0 ) { this . _headElement = document . getElementsByTagName ( "head" ) [ 0 ] ; } return this . _headElement ; } private _cssStyleSheet : CSSStyleSheet ; private get cssStyleSheet ( ) : CSSStyleSheet { if ( ! this . _cssStyleSheet ) { if ( ! document . styleSheets || this . headElement === null ) return null ; this . _cssStyleSheet = Array . from ( document . styleSheets ) . find ( s => ! s . disabled && ( s . media . mediaText == "" || s . media . mediaText . indexOf ( "screen" ) !== - 1 ) ) as CSSStyleSheet ; if ( ! this . _cssStyleSheet ) this . _cssStyleSheet = this . createCssStyleSheet ( ) ; } return this . _cssStyleSheet ; } constructor ( ) { } public setStyle ( selectorText , styleName , value ) { let rule = this . getStyleRule ( selectorText ) ; if ( ! rule ) return ; rule . style [ styleName ] = value ; } public setStyles ( selectorText , styles ) { let rule = this . getStyleRule ( selectorText ) ; if ( ! rule ) return ; Object . keys ( styles ) . forEach ( styleName => { rule . style [ styleName ] = `${ styles [ styleName ] }` ; } ) ; } private createCssStyleSheet ( ) { let styleSheetElement = document . createElement ( "style" ) ; styleSheetElement . type = "text/css" ; this . headElement . appendChild ( styleSheetElement ) ; return styleSheetElement . sheet as CSSStyleSheet ; } private getStyleRule ( selectorText ) { if ( ! this . cssStyleSheet ) return ; let rules = this . cssStyleSheet . cssRules . length > 0 || this . cssStyleSheet . rules . length == 0 ? this . cssStyleSheet . cssRules : this . cssStyleSheet . rules ; let rule = Array . from ( rules ) . find ( r => r instanceof CSSStyleRule && r . selectorText . toLowerCase ( ) == selectorText . toLowerCase ( ) ) as CSSStyleRule ; if ( ! rule ) { let ruleIndex = this . cssStyleSheet . insertRule ( selectorText + "{ }" , rules . length ) ; rule = rules [ ruleIndex ] as CSSStyleRule ; } return rule ; } }