Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular 13 Cannot get rid of Object is possible null

I have some code that contains this:

var element = document.getElementById("div0");
    element.parentNode.removeChild(element); // Error points here

I keep getting:

object is possibly 'null' and tried added ! to element but it still complains.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get rid of this error?

>Solution :

As already mentioned by @Sh. Pavel it is a Typescript error.

From my point of view you have several options but I just point out two options, which I think are the best for your issue.

Option 1: Optional Chaining

By using optional chaining the code stops the execution if it runs into a null or undefined. Also, it produces cleaner and less code than adding a guard for each potentially nullable property.

const element = document.getElementById("div0");
element?.parentNode?.removeChild(element);

Option 2: Guard

By using a guard the code part can only be reached if the condition is true, so Typescript understand that the values are defined then

const element = document.getElementById("div0");
if (element && element.parentNode) {
  element.parentNode.removeChild(element);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading