document.getElementById('msg')
will return the element that has the id "msg" if it exists. But it might not exist. This is why the response is not a HTMLElement
but a HTMLElement | null
.
This means that you have to handle the null
case. This is the meaning of the error message Object is possibly 'null'
.
If you know that the element always exists, you can assert that it is not null
, like this:
document.getElementById('msg')!.innerHTML
^
Or, if it can be null
, you can use a if/else
statement
const element = document.getElementById('msg')
if (element) {
const innerHTML = element.innerHTML;
[...]
} else {
[...]
}
That would solve the problem but I have to add that you normally never have to get elements with document.getElementById
in Angular. This would "work" but is not the correct way of doing it.
It would be better to use the ViewChild
syntax (see doc).
In html, mark the targeted element with a name, like this :
<div id="msg" #msgElement>
[...] ^^^^^^^^^^^
</div>
And, on TypeScript side :
@ViewChild('msgElement')
msgElement?: HTMLElement
Beware, the ViewChild
is initiated only after the AfterViewInit()
method of the Angular lifecycle. If you try to call it too soon, like in the constructor
or OnInit()
, you will get undefined