Skip to main content

angular - Generate random number in range

app.component.ts

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

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


export class AppComponent {
  randomNumberInt: number = -1;

  generateRandomNumberInRange(min: number, max: number) {
    // Minimum and maximum number both included 
    this.randomNumberInt = Math.floor(
      Math.random() * (max - min + 1) + min
    );
  }
}
app.component.html

<h2>Angular - Random Number In Range</h2>

<ng-template [ngIf]="randomNumberInt>=0">
    Random Number Int: {{randomNumberInt}}
</ng-template>

<br/><br/>
<button 
    (click)="generateRandomNumberInRange(0,10)" 
    style="padding:12px;">
        Get Random Number
</button>
More Angular tutorials