我想更改包裹在父元素内部的子元素的字体样式,该父元素又被其他元素内部包裹,最后它被包含在影子根内。附上 DOM 树结构 -
我尝试通过以下代码进行更改
let host = document.querySelector(".fs-timescale-dd");
// host.setAttribute('style','font-style:normal');
let child= host.querySelector('.select');
child.querySelector('.ng-select').querySelector('.ng-select-container')
.querySelector('ng-value-container').querySelector('ng-placeholder')
.setAttribute('style','font-style:normal');
但是我收到 TypeError: Cannot read properties of null (reading 'querySelector')
我是 Angular 新手,有人可以帮忙吗。
您没有明确提及您的目标。阅读您的问题后,我可以理解的是您想更改下拉菜单选项的字体样式。如果是这样,您可以通过以下示例执行此操作。您可以直接选择要应用样式的类。
::ng-deep .some-class {
font-style: normal;
}
通过添加类名引用shadow dom元素来解决。 像这样的东西-
document.querySelector(".fs-timescale-dd").className('someName').shadowRoot.setAttribute("font","arial")
您可以使用
renderer2
+ ViewChild
来强制使用 ShadowDom 的子样式。例如:
import { Component, ElementRef, Renderer2, AfterViewInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div class="fs-timescale-dd" #hostElement>
<!-- Shadow DOM structure -->
</div>`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('hostElement', { static: false }) hostElementRef!: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit(): void {
const host = this.hostElementRef.nativeElement;
if (host) {
const shadowRoot = host.shadowRoot;
if (shadowRoot) {
const placeholder = shadowRoot.querySelector('.ng-placeholder');
if (placeholder) {
this.renderer.setStyle(placeholder, 'font-style', 'normal');
}
}
}
}
}