angular - 将 ngStyle 绑定到指令的动态 ElementRef
问题描述
我开发了一个指令来动态地将 elementRef 添加到当前元素。是否可以将 ngStyle 指令绑定到动态创建的 elementRef。
dynamicElementStyle: { [key: string]: string; };
constructor(private _element: ElementRef, private _renderer: Renderer2) { }
@HostListener('mouseover') onHover() {
this.dynamicElementStyle.background-color = "red";
}
@HostListener('mouseleave') onHover() {
this.dynamicElementStyle.background-color = "green";
}
public ngOnInit(): void {
const dynamicElement = this._renderer.createElement('div');
/* How to bind dynamicElementStyle to this dynamicElement */
this._renderer.appendChild(this._element.nativeElement, dynamicElement);
}
我不会使用 Renderer2.setStyle() 来应用样式,而是使用对象。它可以是 ngStyle 以及 ngClass、ngIf 等......
解决方案
推荐阅读
- python - Pygame 不会将图像粘贴到画布上
- ms-access-2016 - 根据多个组合框过滤查询,但如果组合框为空,则显示所有记录,包括空,
- jenkins - 如何在 Jenkins 中通过电子邮件发送测试报告
- python - 使用 API 获取 GCC 包含和定义
- javascript - 将附加信息传递给由 `redux-actions` 处理的错误
- knex.js - 从 Knex.js 获取连接池统计信息
- java - java.io.IOException:连接上的流意外结束?
- javascript - AWS CDK 用户池授权者
- azure-ad-b2c - 使用用户名登录的 Azure AD B2C 自定义策略
- ruby-on-rails - ActiveModel 序列化器:将属性作为方法访问