Reputation: 379
In my Angular project Typescript code I am getting the error:
Object is possibly 'null'
on this line:
document.querySelector<HTMLElement>('.highlighted').style.backgroundColor = 'white';
If I add ?
to above line like this:
document.querySelector<HTMLElement>('.highlighted')?.style.backgroundColor = 'white';
then I get the following error:
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
I need help to solve either of these errors.
Upvotes: 1
Views: 6917
Reputation: 41
Angular v12 has strict type and null checks. For this reason, the '!' comes in handy. Can use it as such :
It is good practice to manage with an else condition, assign '!' only when you are sure the object won't be empty.
(Code Context: trying to map the routes with the url containing param-> id)
Upvotes: 1
Reputation: 51896
document.querySelector()
can return null
. Assign it to a variable, then use an if
statement to assert that it is not null before assigning to one of its properties:
const element = document.querySelector<HTMLElement>('.highlighted');
if (element) {
element.style.backgroundColor = 'white';
}
Alternatively if you know from the context of your program that this query will not return null
, you can use a TypeScript non-null assertion (!
):
document.querySelector<HTMLElement>('.highlighted')!.style.backgroundColor = 'white';
Upvotes: 5