Angular Styles are not applying to renderer2 created elements

1.2k views Asked by At

Inside app component

import { Component, ViewChild, Renderer2, ElementRef } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
//I'm using renderer2 inside component not directory

export class AppComponent {
  @ViewChild('div1') el : ElementRef;
  showComment = false;
  constructor(private renderer: Renderer2){}
  ngOnInit() {}

  ngAfterViewInit() {
    const div = this.renderer.createElement('div');
    div.innerHTML=`<p id='comment' #comment1 *ngIf='showComment'>Test<p>`;
    this.renderer.appendChild(this.el.nativeElement, div);
  }
}

styles are not applying to 'div' and 'p' tag created with renderer2 inside 'app.component.css.

I can't even view that using viewchild,and ngif is also not working ,does that not belongs to app component.

How can i apply styles in the same component** except adding styles globally, how can i make *ngif work.Im new to Angular please help.

2

There are 2 answers

2
IAfanasov On

It seems like ViewEncapsulation issue. ViewEncapsulation.None might solve it:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent {
  ...
}
0
ARZMI Imad On

You can use ::ng-deep to style you p element

::ng-deep #comment { // your style}