In this blog, we will learn about how to set counter in angular project.
Step 1:
Create an Angular Application
ng new Counter
Step 2:
Install node_modules
npm install
Step 3:
In app.component.html
<h2>{{counter1}}</h2> <h2>{{counter2}}</h2>
Step 4:
In app.component.ts
import { Component } from '@angular/core'; import { interval, Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { counter1 = 0; counter2 = 0; value1 = 50; value2 = 70; timerSubscription1!: Subscription; timerSubscription2!: Subscription; constructor() { this.timerSubscription1 = interval(70).pipe(map(() => this.valueCounter1())).subscribe(); this.timerSubscription2 = interval(70).pipe(map(() => this.valueCounter2())).subscribe(); } valueCounter1() { this.counter1++ if (this.counter1 >= this.value1) { this.timerSubscription1.unsubscribe() } } valueCounter2() { this.counter2++ if (this.counter2 >= this.value2) { this.timerSubscription2.unsubscribe() } } }
Step 5:
Now Run the Application
npm start