skip to Main Content

I would like to apply the CSS to the element created in TypeScript. Is this possible without adding the style in TypeScript (test.style.color = ‘red’;)?

My HTML:

<div class="testContainer">
  <p>Created in HTML</p>
  <!--  Created in TS-->
</div>

My TypeScript:

ngOnInit() {
    let container = document.querySelector('.testContainer')
    if(container) {
      let test = document.createElement('p');
      test.textContent = "Created in TS"
      container.append(test)
    } else {
      console.log('TestContainer not found')
    }
  }

My CSS:

p {
  color: red;
}

I tried to add classes to the elements, created in the TypeScript file. They were displayed in the developer tools of my browser, but the CSS wasn’t applied.

2

Answers


  1. You can directly add class to the element, created in the TypeScript file.

    TypeScript Code

    test.textContent = "Created in TS";
    test.setAttribute("class","MyClass");
    container.append(test);
    

    CSS

    .MyClass {
        color: green !important;
     }
    
    Login or Signup to reply.
  2. Why not work:

    The way Angular manage the .css (to isolate the .css of each element) is adding a prefix in .css. So if you check the .html using F12 in your navigator

    You see a .css like

    p[_ngcontent-ng-c474887881] {
      color: red;
    }
    

    And a .html like

    <div _ngcontent-ng-c474887881="" class="testContainer">
       <p _ngcontent-ng-c474887881="">Created in HTML</p>
       <p>Created in TS</p>
    </div>
    

    (the _ng-content-ng-c474887881] can be another one, it’s only to explain me.

    So, when you create using simple javascript your "divs" has not the attribute _ngcontent-ng-…, and not get the .css

    Solutions:

    1. You can use a global .css (adding in styles.css or using
      ViewEncapsulation.None), but in this case the .css is applied to all
      the application, and to make the .css it’s only to the element
      created you need add a class to your element to be more specific the
      .css

    2. The another way is use Renderer2

        const container = document.querySelector('.testContainer') //(*)
      
        const div = this.renderer.createElement('p');
        const text = this.renderer.createText('Created in TS by renderer2');
      
        this.renderer.appendChild(div, text);
        this.renderer.appendChild(container, div);
      

      (*) I prefer use a template reference variable and ViewChild,

      In your .html

      <div #container>
        <p>Created in HTML</p>
        <!--  Created in TS-->
      </div>
      

      In .ts

      //I use static true because the div is NOT under a *ngIf
      @ViewChild('container',{static:true}) container!:ElementRef
      
      //and use
       this.renderer.appendChild(this.container.nativeElement, div);
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search