Skip to main content

angular - How to generate random number

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;
  randomNumberFloating:number = -1;
  
  generateRandomNumberInt(){
    // Generate random integer from 0 to 9
    this.randomNumberInt = Math.floor(Math.random()*10);
  }

  generateRandomNumberFloating(){
    // Random number between 0 (inclusive),  and 1 (exclusive)
    this.randomNumberFloating = Math.random();
  }
}
app.component.html

<h2>Angular - Generate Random Number</h2>

<ng-template [ngIf]="randomNumberInt>=0">
    Random Number Int: {{randomNumberInt}}
</ng-template>
<br/>
<button (click)="generateRandomNumberInt()" style="padding:12px;">
    Get Random Number Int
</button>

<br/><br/>
<ng-template [ngIf]="randomNumberFloating>=0">
    Random Number Floating: {{randomNumberFloating}}
</ng-template>
<br/>
<button (click)="generateRandomNumberFloating()" style="padding:12px;">
    Get Random Number Floating
</button>
More Angular tutorials