Angular 12 对象可能是 'null' in document.getElementById(elementId)
Angular 12 Object is possibly 'null' in document.getElementById(elementId)
在 Angular 12 中,我一直遇到这个问题:
我想通过 id 显示一个元素...所以我有这个:
document.getElementById(elementId).style.visibility = 'hidden';
我不断得到:
Object is possibly 'null'.
我不知道它在说什么:(
我怎样才能阻止这个错误?
检查 getElementById
中的 returned 值是否不为空:
const element = document.getElementById(elementId);
if (element) {
element.style.visibility = 'hidden';
}
getElementById
的 return 类型是 HTMLElement | null
,因为函数很可能找不到元素。
您 可能确定该元素存在,但您的代码不知道。
在 Angular 12 中,我一直遇到这个问题:
我想通过 id 显示一个元素...所以我有这个:
document.getElementById(elementId).style.visibility = 'hidden';
我不断得到:
Object is possibly 'null'.
我不知道它在说什么:(
我怎样才能阻止这个错误?
检查 getElementById
中的 returned 值是否不为空:
const element = document.getElementById(elementId);
if (element) {
element.style.visibility = 'hidden';
}
getElementById
的 return 类型是 HTMLElement | null
,因为函数很可能找不到元素。
您 可能确定该元素存在,但您的代码不知道。