typescript - Angular 樣式未應用於 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 也不起作用,它不屬於 App 組件嗎。
我如何在同一個元件中套用樣式** 除了全域新增樣式之外,我要如何讓 *ngif 能夠運作。我是 Angular 新手,請幫忙。
答案#1
這似乎是 ViewEncapsulation 的問題。ViewEncapsulation.None 可能可以解決它:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
export class AppComponent {
...
}
答案#2
你可以使用 ::ng-deep 來設計你的 p 元素
::ng-deep #comment { // your style}
