如何在 Angular 中使用 ElementRef 访问 ::after 伪选择器



例如,如何访问和设置下面元素的 ::after 伪选择器的背景颜色?

@ViewChild('infobubble', { read: ElementRef }) infoBubbleElement: ElementRef;
ngAfterViewInit(): void {
const elem = this.infoBubbleElement.nativeElement;
elem.style.backgroundColor = 'green';
}

我遇到了同样的情况,无法从 elementRef 访问 ::before 或 ::after HTML 元素;我的解决方案是在我需要访问的 HTML 元素中创建另一个 DIV,使用指令对其进行修改并更改div 的背景,这将是新的 :: 之前

示例我的指令:

@Directive({selector: '[appPrimaryColor]'})
export class PrimaryColorDirective implements OnInit {
@Input() backgroundColor = false;
constructor(
private elementRef: ElementRef,
private _renderer: Renderer2,
) { }
ngOnInit() {
// Set BackgroundColor
if (this.backgroundColor) {
this._renderer.setStyle(this.elementRef.nativeElement, 'background-color', COLOR);
}
}
}

在 HTML 中:

<div class="icon">
<!-- step-ok-effect is the new div-->
<div
appPrimaryColor
[backgroundColor]="true"
class="step-ok-effect"></div>
<span class="icon-{{ step.state ? 'check' : step.icon }}"></span>
</div>
</div>

最新更新