我有一个自定义 Angular 组件,由我在 Angular 组件内使用的第三方库动态添加一个 HTML 元素。特定的第三方库是无关紧要的,因为我正在寻找一种可以与各种第三方库一起使用的解决方案。
我想向这些动态添加的 HTML 元素应用/添加 Angular 的模拟封装属性(例如 _ngcontent-c1
)。如果存在的话,我更喜欢官方方法(我无法找到这样的方法),或者其他相当可靠的方法。
最佳答案
这是我找到的一种非官方方法:
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
const attrs = this.hostRef.nativeElement.attributes
for (let i = 0, l = attrs.length; i < l; i++) {
if (attrs[i].name.startsWith('_nghost-c')) {
return `_ngcontent-c${attrs[i].name.substring(9)}`
}
}
}
ngAfterViewInit() {
// dynamically add HTML element
dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}
NOTE: This does allow you to style the dynamically added HTML element.
我的猜测是,这个属性的约定不能保证在 Angular 版本之间保持稳定,因此在升级到新版本时可能会遇到此解决方案的问题(尽管,更新此解决方案可能是微不足道的)这种情况)。
如果 Angular 公开一个类似于 getContentAttr 的函数,稍微抽象一下内部实现,那就太好了。
关于css - 如何将 Angular 的模拟封装属性应用于动态添加到 Angular 组件的 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913172/