As part of angular 6 to 15 migration, I have to update jquery as well. earlier we have used
"@types/jquery": "2.0.33"
"jquery": "3.1.1"
As part of package.json, since we have upgraded to angular, we have jquery as below:
"jquery": "^3.6.4",
"@types/jquery": "^3.5.16"
In one of the places we have used the below query function in the .ts file
this.cssService.setElHeight($('.div .content h4'));
Below is the service method:
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);
}
}
at line " let max_height = $(this).height() ?? 0;
" we get error as below:
" Cannot read properties of undefined (reading 'defaultView')"
Instead of $(this)
I tried $(element)
, but some of the content don’t get proper height.
2
Answers
I have got it working following way: it might be useful to someone who is in same need:
Avoid directly manipulating the DOM using jQuery or any other external library. Angular provides its own way of interacting with the DOM using ElementRef and Renderer2.
Import ElementRef and Renderer2 from @angular/core:
Inject ElementRef and Renderer2 into your service’s constructor:
Modify your setElHeight method to use Renderer2 instead of jQuery:
Update your template to pass the ElementRef to the setElHeight method
hope it’s work perfectly
Using JQuery