TypeError: Cannot read property 'classList' of null


#1

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’);


#2

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


#3

To add extra styles to it.


#4

I would suggest using property binding instead.


#5

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);
}

#6

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

#7

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


#8

Thanks salvatojalva. I solved that issue by using viewChild.


#9

:facepalm:

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


#10

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


#11

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>

#12

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


#13

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