Skip to main content

angular - How to use setInterval()

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  counter:number = 0;
  isDisabled:boolean = false;

   onClick(){
    this.isDisabled = true;
    // Repeat executing a function at a specified time interval.
    setInterval(() => this.updateCounter(), 1000)
   }

   updateCounter(){
    this.counter++;
   }
}
app.component.html

<h2 style="padding-top:25px; padding-bottom:25px;">
    Angular - How to use setInterval()
</h2>

<button 
    (click)="onClick()" 
    [disabled]="isDisabled"
    style="margin-bottom:20px; padding:12px;">
        Start Counting (1 second interval)
</button>

<h1>Counter : {{counter}}</h1>
More Angular tutorials