作为angular 6到15迁移的一部分,我还必须更新jquery。之前我们使用
"@types/jquery": "2.0.33"
"jquery": "3.1.1"
作为package.json的一部分,由于我们已经升级到angular,我们有如下的jquery:
"jquery": "^3.6.4",
"@types/jquery": "^3.5.16"
在其中一个地方,我们在.ts文件中使用了下面的查询函数
this.cssService.setElHeight($('.div .content h4'));
以下是服务方法:
setElHeight(element: any) {
element.height('auto');
if (element.length) {
let maxheight: number = 0;
element.each(() => {
let max_height = $(this).height() ?? 0; //here I get error Cannot read properties of undefined (reading 'defaultView')
maxheight = (max_height > maxheight ? max_height : maxheight);
});
element.height(maxheight);
}
}
在“let max_height = $(this).height() ?? 0;
“行,我们得到如下错误:
" Cannot read properties of undefined (reading 'defaultView')"
而不是$(this)
我尝试了$(element)
,但有些内容没有得到适当的高度。
2条答案
按热度按时间8dtrkrch1#
避免使用jQuery或任何其他外部库直接操作DOM。Angular提供了自己的方式,使用ElementRef和Renderer 2与DOM进行交互。
从@angular/core导入ElementRef和Renderer 2:
将ElementRef和Renderer 2注入到服务的构造函数中:
修改setElHeight方法以使用Renderer 2而不是jQuery:
更新模板以将ElementRef传递给setElHeight方法
希望一切顺利
Using JQuery
rjzwgtxy2#
我已经得到了它的工作方式如下:它可能对有同样需要人有用: