Hello, I am working in universal Angular and I have the following function
private validateBox() {
const divHeight: any = document.getElementById('product-detail-images').getBoundingClientRect();
if (divHeight) {
if (divHeight.top > -2491) {
this.isAbsolute = false;
this.cd.markForCheck();
} else {
this.isAbsolute = true;
this.cd.markForCheck();
}
}
}
The problem is that document.getElementById('product-detail-images').getBoundingClientRect()
it gives me an error in the console. error TS2531: Object is possibly 'null'.
It's a compiler error, because you're not checking whether the element exists or not, but you do have a check on whether the height is 0 or not. You should check it like this:
The exclamation mark is the "check not null" operator, if the call to
document.getElementById
isnull
, it will not cause an error but will make div equalnull
This is because you probably have the flag enabled in your tsconfig file
strict null checks
. This is a feature to avoid runtime errors.