角度样式不适用于renderer2创建的元素

问题描述

内部应用程序组件

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);
  }
}

样式不适用于在app.component.css中使用renderer2 创建的'div'和'p'标签

我什至看不到使用viewchild,并且ngif也不起作用,这不属于应用程序组件。

除了在全局添加样式外,如何在同一组件中应用样式**,我该如何使*ngif工作。Angular的新手请帮忙。

解决方法

似乎是ViewEncapsulation问题。 ViewEncapsulation。没有人可以解决它:

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