document.getElementById('msg').innerHTML getting error for angular 13

Asmita Patil

Help to resolve this. Want to contact the data I tried all possible ways

(method) Document.getElementById(elementId: string): HTMLElement | null

Returns a reference to the first object with the specified value of the ID attribute.

@param elementId — String that specifies the ID value.

Object is possibly 'null'.ts(2531)

Arnaud Denoyelle

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324180615&siteId=291194637