2

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.

4
  • This is because of default angular sanitization. You can`t directly add html string to tag. It will consider it as a injecting malicious code. You need to import sanitization in constructor, and explicitly you have to tell angular that i am okay to this innerHTML string and it is safe bypassSecurityTrustHtml Commented Oct 8, 2020 at 12:07
  • after importing in constructor how can i do it Commented Oct 8, 2020 at 12:25
  • I guess you need bypassSecurityTrustHtml method Commented Oct 8, 2020 at 19:51
  • Tried but not working Commented Oct 17, 2020 at 14:25

2 Answers 2

1

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 {
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

But its same as applying style globally
I want to encapsulate syles with component
0

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

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

Comments