TypeError: Cannot read property 'classList' of null

Getting error like.

ERROR TypeError: Cannot read property ‘classList’ of null
at RegisterPage.webpackJsonp.781.RegisterPage.push

Error is occurring here…

this.navLayout = document.querySelector(’.layout’)
this.navLayout.classList.toggle(‘layout–active’);

Direct DOM access in an Angular application is extremely unidiomatic. Why are you doing it?

2 Likes

To add extra styles to it.

I would suggest using property binding instead.

You are trying access to “classList” of an element who probably isn’t exist in this moment, try to access to “classList” in the event ionDidLoad()

Try something like that:

toolbar: any = document.getElementsByClassName("toolbar");

------------

ionViewDidLoad() {
      setTimeout(() => {
          this.toolbar[0].classList.remove('first-load');
      }, 2000);
}

With all due respect to @salvatojalva and their attempt to help the community, I strongly disagree with virtually every aspect of the previous post:

  • abuse of any
  • direct DOM access
  • magic numbers (two of them)
  • needless setTimeout
1 Like

Thanks for the help. It’s solved i used nativeElement.

Thanks salvatojalva. I solved that issue by using viewChild.

1 Like

:facepalm:

Life is a lot easier when you work with the framework, instead of working to subvert it.

I didn’t get you. Is there any way to do that instead of using property binding.

Property binding doesn’t require you to ever type “document” or “nativeElement”:

.layout {
  height: 24px;
  width: 24px;
}

.layout-active {
  border: 4px solid blue;
}
active = false;
<div class="layout" [class.layout-active]="active"></div>
<button (click)="active = !active">toggle activity</button>

Thank you rapropos. I already tried that one working fine. But i tried to do with viewChild for learning purpose.

No, problem, thank you for your observation, always exist best practices to work on ionic, i still learning how to use properly the framework.

1 Like