Aug 21, 2019

Angular: What does "Cannot read property 'childNodes' of null" trying to tell?

Recently, I ran into the following error, it has no obvious problem at first until part of my component template didn't show a thing until a click event is triggered the at the screen.

Cannot read property 'childNodes' of null

The error do not directly indicate which component or code in a template has gone wrong, but you know it's an error about certain part of the code is referring to "childNodes" on a null object.

Finding out the root cause

To find out where in the template has gone wrong, I didn't suspect it's problem with HTML template. I had started with checking my component class code, and though some binding values weren't pass correctly into the template code (the template code look fine, not bad syntax at all!).

Until I gave up trying consciously, I blindly test by removing of the HTML code part by part. This is where it shed me the ray of hope, eventually, I found out it's ion-card Ionic's component doesn't accept [innerHtml] correctly.

If you insist on using ion-card, you need a proper "child node" place inside it (so now I learnt, "child node" means the child element of a parent node "ion-card".), for ion-card, one of the options is ion-card-content.
I changed my code from:

<ion-card [innerHtml]="content" padding></ion-card>

to

<ion-card>
  <ion-card-content [innerHtml]="content"></ion-card-content>
</ion-card>

Separating [innerHtml] from ion-card would solve the childNode problem above. You might have different parent node causing the null childNodes issue too. So to prevent further time wasting effort finding the root-cause and if you run into similar issue, just keep in mind, if you get similar error, it means there is problem in your template/html code.

No comments:

Post a Comment

Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!