skip to Main Content

I’m trying to apply some styling to a div that was created with TypeScript’s CreatElement, but the styles are not being applied.

EDIT: I managed to solve the problem by applying the style in the style.scss global project file but I would like to understand why it worked in this file and not in the component’s scss

component.ts

export class Component implements OnInit {
 bgAnimation!: any;
 numberOfColorBoxes = 400;

 ngOnInit(): void {
  this.bgAnimation = document.getElementById('bgAnimation');
  for (let i = 0; i < this.numberOfColorBoxes; i++) {
    const colorBox = document.createElement('div');
    colorBox.classList.add('colorBox');
    this.bgAnimation.appendChild(colorBox);
   }
 }
}

component.html

<div class="bgAnimation" id="bgAnimation">
 <div class="backgroundAmim"></div>
</div>

component.scss

.colorBox {
 z-index: 2;
 filter: brightness(1.1);
 transition: 2s ease;
 position: relative;
 margin: 2px;
 background: #1d1d1d;
}

2

Answers


  1. Explaining it in a simple way, at ngOnInit the DOM for your component is ready and you are creating those elements manually by javascript and it doesn’t trigger any angular event to check for changes in your component. When you use that class in global style, your browser updates your DOM not angular

    Login or Signup to reply.
  2. it’s because of encapsulation strategy. in default behavior angular use:

    encapsulation: ViewEncapsulation.Emulated
    

    this is default behavior of angular for all components and Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the
    component’s host element and applying the same attribute to all the CSS selectors provided. If you manually add a class using document, that specific attribute will not be added to that class.

    if you want component styles to work properly you have to use ViewEncapsulation.None or
    ViewEncapsulation.ShadowDom.

    If you use ShadowDom, you cannot access the elements using document.getElementById. you have to access them with ViewChild.

    here is an example for ShadowDom sterategy.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search