Reputation: 21
I am working on angular 8 project and was trying to add page screen overlay but facing ERROR TypeError: Cannot read property 'style' of null. I have added button, on which I m making style.display = 'none' OR 'block'. My code work properly on Local but after deploying on firebase using "ng build --prod" I got error. Here are my files
index.html file
<div id="loader-overlay">
<div class="spinner-container">
<div class="loader"></div>
</div>
</div>
</div>
Styles.scss File
#loader-overlay-container {
position: absolute;
z-index: 10000000;
top:0;
}
#loader-overlay {
display: none;
height: 100vh;
width: 100vw;
background-color: #333;
opacity: 0.5;
}
shared.service.ts
// To ADD Page loader screen
enablePageLoaderOverlay() {
document.getElementById('loader-overlay').style.display = 'block';
}
// To REMOVE Page loader screen
disablePageLoaderOverlay() {
document.getElementById('loader-overlay').style.display = 'none';
}
booking.component.ts
onBookService(name: string) {
// To ADD Page loader screen
this.sharedService.enablePageLoaderOverlay();
this.sharedCartService.addToCart(this.services[name], "book");
}
Upvotes: 1
Views: 2076
Reputation: 30198
This is the WRONG way to use Angular... instead it should be
<div *ng-if='IsLoaderShown">
<div class="spinner-container">
<div class="loader"></div>
</div>
</div>
Then in your code:
IsLoaderShown = true;
hide(): void {
this.IsLoaderShown = false;
}
show(): void {
this.IsLoaderShown = true;
}
Upvotes: 0
Reputation: 73
I think the issue is that you have your DOM-elements in the index.html file.
working stackblitz:
https://stackblitz.com/edit/angular-ivy-6286ot?file=src/app/app.component.html
<button (click)="hide()">Hide</button>
<button (click)="show()">Show</button>
<div id="loader-overlay">
<div class="spinner-container">
<div class="loader"></div>
</div>
</div>
--
hide(): void {
document.getElementById("loader-overlay").style.display = "none";
}
show(): void {
document.getElementById("loader-overlay").style.display = "block";
}
However, I would recommend using ViewChild instead of searching with getElementById.
https://angular.io/api/core/ViewChild
Upvotes: 1