css - 如何在 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 的背景,这将是新的 :: before
例如我的指令:
@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>
推荐阅读
- java - 带有样式单元格的 JavaFX.ListView 显示重复列表 (Java)
- r - Map2_df 和命名参数
- primefaces - Primefaces tieredMenu,仅限 Chrome 的错误 - 子项与菜单断开连接
- python - 在 Python 中将字符串与生成的 RDF 实体匹配
- javascript - 如何使用 JavaScript 将多个输入值添加到表中?
- java - 如何在 Appium 中列出列表中的所有元素
- python - 将文本从一个单元格复制到另一个单元格而不删除原始内容python
- git - 无法 ping github,但可以在我的工作场所通过浏览器访问 github。我运气不好?
- flutter - Flutter 错误原因:SocketException: Failed to create server socket (OS Error: Failed to start accept), address = localhost, port = xxxx
- python - Altair 生成带有水平连接表的水平条形图