Rendering <style> inside Component with Renderer (Angular 7)


I have issue with rendering inside component. I would like to emit data from another component and send to another component, data was emitted, but the problem is when I create the element with Renderer2, sometimes it’s working, but sometimes not. Probably it’s a problem with rendering style element in a component?

My service method for emitting data

private globalStyles = new BehaviorSubject<string>('');
formDesign(data: any) {;

Here I emit data from Reactive Form control and send to another component.

// Height
      .subscribe(height => {
        this.showDataCriteria = {
          width: this.formGlobal.controls['width'].value + 'px',
          height: height + 'px'

Here I’m getting data from aside.component.ts and it received!

   * Generate CSS
  generateCss() {
    let basicStyles = ' ';
    let newStyle: HTMLElement;
    let style: HTMLElement = this.document.getElementById('custom-class');
      ? (newStyle = style)
      : (newStyle = this.renderer.createElement('style'));

    this.renderer.setAttribute(newStyle, 'id', 'custom-class');
    let completeStyleFields = '';
      ? (basicStyles += `#${} {${}}`)
      : (basicStyles += '');
    this.customStyle.sections.forEach(element => {
      completeStyleFields += `#${} {${element.textProps}}`;
    basicStyles += completeStyleFields;
    const text = (this.document.textContent = basicStyles);
    newStyle.innerText = text;
    this.renderer.appendChild(this.dndComponent.nativeElement, newStyle);

The Main problem is after style element was created, and I’m seeing the element in the DOM, styles not accepting! Sometimes accepting, and sometimes not. What should I do? How manipulate reload page probably to inject component and styles element?
Short UPD:
After all, I’m seeing #4152ae54-8a9d-49d5-a33d-62dfbbd35890 {height:600px; width:812px; }
But styles not accepted to the elements!


CSS can’t render if the first numeric letter (#4152ae54-8a9d-49d5-a33d-62dfbbd35890). That’s because even though HTML5 is quite happy for an ID to start with a number, CSS is not. CSS simply doesn’t allow selectors to begin with a number. The relevant part of the specification states.

Answered By – Николай Кузьмин

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.