我正在开发一个上下文菜单,我需要在渲染之前获取菜单和每个子菜单的大小。我过去这样做的方法是将元素结构附加到dom,计算bbox,行高等。然后将其删除,以便它永远不会对用户可见。
从这个操作中我得到了我需要检查菜单是否在屏幕外等等所有内容。然后可能会对其进行更改。
在角度2中,如果ViewEncaptulation设置为None,我可以这样做。但是如果我使用它,我在当前的构建设置中会出错,所以我坚持使用默认值。
有谁知道如何以编程方式创建元素并使其从ViewEncaptulation中获取相同的类?
答案 0 :(得分:0)
private elementRef: ElementRef
getEncapsulationId(): string {
if (!this.elementRef) {
return '';
}
var attr = this.elementRef.nativeElement.attributes;
for(let i = 0; i < attr.length; i++){
let s = attr[i].name;
if(s.includes('_nghost')){
return '_ngcontent' + s.substring(7);
}
}
return '';
}
创建元素时,我将封装ID添加为属性。
var element = document.createElement('div');
element.setAttribute(this.getEncapsulationId, '');
element.classList.add('some-class');
如果有人能更好地解决这个问题,请告诉我。