Angular StrictNullChecks:"Object is possibly 'null' "
Angular StrictNullChecks: "Object is possibly 'null' "
我的 Angular 在我的项目中显示“strictNullChecks”。现在,我在模板中有一堆这样的错误 (.html):
<input
#inputValue
type="text"
(keyup.enter)="showStyle(inputValue.value)"
/>
<p id="addStyle" style="color: blue; display: none" #hide>HELLO</p>
(.ts):
addingStyle = window.document.getElementById("addStyle") as HTMLParagraphElement;
showStyle(inputValue: string) {
if (inputValue === "help") {
this.addingStyle.style.display = "block";
console.log("help");
} else {
console.log("it worked");
}
}
它显示如下错误:
Object is possibly 'null'.
我不确定这个错误是针对 addingStyle
还是 inputValue
但在 tsconfig.json
中,您可以关闭 strictNullChecks:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"strictNullChecks": true,
"outDir": "./dist"
},
"include": [
"src/**/*"
]
}
中所述
使用非空断言运算符!在可空表达式的末尾以避免此类错误。
component.ts
addingStyle = window.document.getElementById("addStyle")! as HTMLParagraphElement;
component.html
<input
#inputValue
type="text"
(keyup.enter)="showStyle(inputValue!.value)"
/>
我的 Angular 在我的项目中显示“strictNullChecks”。现在,我在模板中有一堆这样的错误 (.html):
<input
#inputValue
type="text"
(keyup.enter)="showStyle(inputValue.value)"
/>
<p id="addStyle" style="color: blue; display: none" #hide>HELLO</p>
(.ts):
addingStyle = window.document.getElementById("addStyle") as HTMLParagraphElement;
showStyle(inputValue: string) {
if (inputValue === "help") {
this.addingStyle.style.display = "block";
console.log("help");
} else {
console.log("it worked");
}
}
它显示如下错误:
Object is possibly 'null'.
我不确定这个错误是针对 addingStyle
还是 inputValue
但在 tsconfig.json
中,您可以关闭 strictNullChecks:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"strictNullChecks": true,
"outDir": "./dist"
},
"include": [
"src/**/*"
]
}
使用非空断言运算符!在可空表达式的末尾以避免此类错误。
component.ts
addingStyle = window.document.getElementById("addStyle")! as HTMLParagraphElement;
component.html
<input
#inputValue
type="text"
(keyup.enter)="showStyle(inputValue!.value)"
/>