Skip to main content

angular - How to do a task after a delay

app.component.ts

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

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


export class AppComponent {
  message: string = "Lorem ipsum dolor sit amet,"
   + "consectetur adipiscing elit. In at ante mattis,"
   + "sollicitudin arcu id, dictum orci."
   + "Mauris laoreet tincidunt tellus vel faucibus."

   onClick(){
    this.delay(5).then(()=>{
        this.message = "I am changed after 5 seconds on button click."
      }
    );
   }

   delay(seconds:number) {
    return new Promise(resolve => setTimeout(resolve, seconds * 1000));
  }
}
app.component.html

<h2 style="padding-top:25px; padding-bottom:25px;">
    Angular - How to do a task after a delay
</h2>

<button 
    (click)="onClick()" 
    style="margin-bottom:20px; padding:12px;">
        Change Text (delay 5 seconds)
</button>

<h3>{{message}}</h3>
More Angular tutorials