Reputation: 107
I've created a skeleton structure for my app in Angular 9. The skeleton code initializes in ngAfterViewInit()
hook.
ngAfterViewInit() {
this.showSpinner = false;
this.interval = setInterval(() => {
this.domLoaded = true;
}, 5000);
}
I have also used ngAfterContentInit()
but that didn't work
Upvotes: 0
Views: 5060
Reputation: 313
There are a lot of ways to go about with this (also, I do agree with the comment by Pardeep - you should look for other ways) but sticking to your question, try to save the state within localStorage/sessionStorage so that the information is not lost after navigating to other pages in your site. So something like this will work:
ngAfterViewInit() {
this.showSpinner = false;
if (!sessionStorage.getItem('siteInit')) {
this.interval = setInterval(() => {
this.domLoaded = true;
sessionStorage.setItem('siteInit', 'true');
}, 5000);
} else {
this.domLoaded = true;
}
}
Upvotes: 1
Reputation: 790
Assuming you placed <router-outlet></router-outlet>
in app.component.ts
, this component will only load once and the subsequent navigation will happen within the application (Single Page Application benefits).
Therefore, you can run the code right there if this is what you need.
If you want to only run the code once the first time a user accesses your page and not run it for subsequent refreshes, you can use the browser Local Storage to keep track of the state (mark if it's the first time accessing the page or not). Then you'd need to check on every page load whether you need to run the code or not.
Strictly related to your question, if you're tracking the state of a spinner
, you most likely want it to run on every page refresh. For this you can hold its state in a Service instead of Local Storage.
Side note: Accessing browser's Local Storage is much more inefficient than accessing a variable that's already in memory.
Upvotes: 0
Reputation: 1020
The ngAfterViewInit()
lifecycle hook gets called every time, your component is loaded. To achieve your required functionality you could use a Singleton Service and set the domLoaded
property there.
Upvotes: 0