Ways to trigger an Angular function once and persist it even after the component is reloaded

Currently, I am learning Angular and have come across a particular issue. As far as I understand, everything placed within the `ngOnInit` method gets executed every time the component reloads. I have a timer function that needs to continue running even after the page is reloaded, without resetting the count. Is there a way to execute the `startTimer(secsToStart: number)` function outside of `ngOnInit`, in the HTML file, or should I explore other Angular features for this purpose?

Here is the code snippet for the component:

@Component({
  selector: 'app-task-countdown',
  templateUrl: './task-countdown.component.html',
  styleUrls: ['./task-countdown.component.css'],
})
export class TaskCountdownComponent implements OnInit {
  @Input()
  tasks!: Tasks[];
  excuse!: Loosers[];
  excuseForm!: FormGroup;
  expirationCounter!: string;
  timeIsUp = false;
  donePushed = false;


  constructor(
    private fb: FormBuilder,
    private tasksService: TasksService,
    private excuseService: ExcuseService,
    private router: Router
  ) {}

  ngOnInit() {
    this.tasks = this.tasksService.getTasks();
    this.startTimer(86400);
    this.excuseForm = this.fb.group({
      excuse: '',
    });
    
    this.excuseForm.valueChanges.subscribe(console.log);
  }

  addExcuse() {
    const excuseValue = this.excuseForm.value;
    this.excuseService.addExcuse(excuseValue);
    this.router.navigate(['/loosers']);
  }

  onTaskDone() {
    this.donePushed = true;
  }


  startTimer(secsToStart: number): void {
    var start: number = secsToStart;
    var h: number;
    var m: number;
    var s: number;
    var temp: number;
    var timer: any = setInterval(() => {
      h = Math.floor(start / 60 / 60);
      temp = start - h * 60 * 60;
      m = Math.floor(temp / 60);
      temp = temp - m * 60;
    
      s = temp;

      var hour = h < 10 ? '0' + h : h;
      var minute = m < 10 ? '0' + m : m;
      var second = s < 10 ? '0' + s : s;

      this.expirationCounter = hour + ':' + minute + ':' + second;

      if (start <= 0) {
        clearInterval(timer);
        this.expirationCounter = 'Expired';
        this.timeIsUp = true;
        this.tasks = [];
      } else if (this.donePushed) {
        clearInterval(timer);
        console.log(start);
      }
      start--;
    }, 1000);
  }
}

In the HTML section, the timer runs and displays `expirationCounter` value inside a span element:

<app-nav-bar></app-nav-bar>

<div *ngFor="let tasks of tasks">
  <p>{{ tasks.task }}</p>
  <button (click)="onTaskDone()">Done</button>
</div>

<div>
  <span id="myTimeCounter">{{ expirationCounter }}</span>
</div>
<div *ngIf="this.timeIsUp">
  <form [formGroup]="excuseForm">
    <input
      type="text"
      placeholder="write down your excuses .. "
      formControlName="excuse"
    />
    <button (click)="addExcuse()">Add</button>
  </form>
</div>

Answer №1

Angular loses all data it has collected, like the current count state, when you refresh the page.

To maintain the current count value, it is recommended to store it in the local storage on each count update and retrieve it from there whenever the page or components load.

// Store count value
let myCount: number = 5;
localStorage.setItem("countValue", String(5));

// Retrieve count value
let storedCount: string = localStorage.getItem("countValue");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript: It is possible that the object is 'undefined' only for the '<' and '>' operators

I've been encountering a very peculiar issue with the error message Object is possibly 'undefined'. My objective is to create a condition similar to this: if (productPages?.length && productPages[productPages.length - 1].docs?.length < 1 ...

Angular functions are self-contained and cannot access anything external to their own scope

I created a classic interceptor for Angular, and now I am working on an interceptor for Syncfusion requests. While I have found a solution, I am facing a problem - I am unable to call a method in my function instance. Here is the snippet of my source code: ...

Incorporating Classname into series data in Angular Highcharts

My current challenge involves applying css class names to the data in a pie chart. I am working on implementing a pie chart with customized colors using Angular Highcharts. I discovered that when using the regular version of Highcharts, the property &apos ...

Configuring webpack for Angular 2 in order to generate bundles as files rather than keeping them in memory

Currently, I am utilizing Angular2 with Webpack, following the setup outlined in the Angular2 webpack introduction. When I run the webpack dev server, it bundles my typescript files and instantly loads them in the browser from memory. However, I require ...

Angular is able to select an element from a specified array

I'm currently struggling with using Angular to manipulate a TMDB API. I am having difficulty retrieving an item from an array. Can someone provide assistance? Here is the response that the array returns: { "id": 423108, "results ...

Utilizing ngModel with an uninitialized object

What is the most effective way to populate an empty instance of a class with values? For example, I have a User Class and need to create a new user. In my component, I initialize an empty User Object "user: User;". The constructor sets some properties, w ...

Is it possible to eradicate arrow functions in Angular CLI?

I am facing a challenge in running my code on IE11 due to issues with arrow functions. I need to find a way to eliminate them from the build and replace them with function() {}. Even though I have removed them from main.js, they are still present in the v ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Webpack and TypeScript are throwing an error stating that `$styles` is not defined

I've encountered an issue with my typescript SharePoint spfx solution. After compiling using webpack, my $styles variable becomes undefined even though I am able to use the class names directly. It seems like there might be a configuration problem at ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Improve the way you manage the active selection of a button

ts isDayClicked: { [key: number]: boolean } = {}; constructor() { } setSelectedDay(day: string, index: number): void { switch (index) { case 0: this.isDayClicked[0] = true; this.isDayClicked[1] = false; this.isDay ...

When item.id matches group.id within the ngFor loop, a conditional statement is triggered

Creating nested columns with matching ids using ngFor seems like a challenge. How can I achieve this? Imagine having an object structured like this: columnNames = [ {id: 0, name: 'Opened'}, {id: 1, name: 'Responded'}, {id: ...

Using Ionic/Angular ion-datetime with specific conditions

In my Ionic app, I have a datetime picker where users can select a time, but with one condition: If the hour is equal to '21', then the minutes must be set to '00' (not '30'). For all other hours, the minutes can be either &ap ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

What is the process for deactivating touch gesture recognition in a particular view within an IONIC3 application?

I am looking to prevent all touch gestures on certain views within my app. Users should only be able to interact with the app using an external keyboard while in these views. I have reviewed the Ionic Docs but couldn't find clear instructions, I onl ...

There are no route parameters defined

Within my user template file, I have a tab control implemented as shown below: <nav md-tab-nav-bar> <a class="tab-label" md-tab-link [routerLink]="'following'" routerLinkActive #following="routerLinkActive" [acti ...

Sharing code between Angular 8 and NodeJS 12: Best practices

Can code be shared between Angular 8 (TypeScript) and NodeJS 12? All the code is located on the same server but in separate directories /client and /server. A major issue we are facing is the duplication of regular expressions and constants across both A ...

Suggestions for importing by Typescript/VS Code

Imagine you have a file called a.ts that contains 4 named imports: export const one = 1 export const two = 2 export const three = 3 export const four = 4 Next, you have a file named b.ts and you want to import some variables from a.ts. import {} from &a ...

What is the process for setting the value of a TextField based on a Dropdown Selection?

I have a question regarding the code snippet below. I am wondering how to set the value of a specific TextField based on the selected item in a Dropdown component named ChildComponent. import * as React from "react"; import ChildComponent from './Ope ...

Do not consider file extensions when using child_process fork with node-dev and Typescript

In my Typescript project, I utilize both node-dev and ts-node in my local development environment. To create a subprocess, I make use of the fork method from child_process, as shown here: fork(path.join(__dirname, './worker.ts')); While this se ...