Skip to main content

angular - How to call function on Button click

app.component.ts

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

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

export class AppComponent {
  randomNumber:number = -1;
  getRandomNumber(max:number){
    this.randomNumber =  Math.floor(Math.random() * max);
  }
}
app.component.html

<h2>Angular - Call Function On Button Click</h2>

<button (click)="getRandomNumber(100)" style="padding:12px;">
    Get Random Number
</button>

<h3 *ngIf="randomNumber>=0">
    {{randomNumber}}
</h3>
More Angular tutorials