Search code examples
domrxjsangular5angular2-templateangular2-services

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?

toolbar.state.service.ts My service method for emitting data

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

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

// Height
    this.formGlobal.controls['height'].valueChanges
      .pipe(debounceTime(500))
      .pipe(distinctUntilChanged())
      .pipe(takeUntil(this.destroy$))
      .subscribe(height => {
        this.formGlobal.controls['height'].setValue(height);
        this.formGlobal.updateValueAndValidity();
        this.showDataCriteria = {
          width: this.formGlobal.controls['width'].value + 'px',
          height: height + 'px'
        };
        this.toolbarStatus.formDesign(this.showDataCriteria);
      });

builder.component.ts 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');
    style
      ? (newStyle = style)
      : (newStyle = this.renderer.createElement('style'));

    this.renderer.setAttribute(newStyle, 'id', 'custom-class');
    let completeStyleFields = '';
    this.customStyle.global
      ? (basicStyles += `#${this.projectInfo.id} {${this.customStyle.global}}`)
      : (basicStyles += '');
    console.log(basicStyles);
    this.customStyle.sections.forEach(element => {
      completeStyleFields += `#${element.id} {${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!


Solution

  • 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.