Home > Enterprise >  how to stop page getting reload on button click in angular
how to stop page getting reload on button click in angular

Time:11-15

how to stop page getting reload on button click in angular.I am creating a quiz application in angular.I am fetching random questions and options from api.on selecting option ,next question is coming as i want to achieve this fuunctionality.but along with it page gets also reload which i dont want.How to stop this

TS File

import { Component,Input,Output,HostListener } from '@angular/core';
import { QuestionService } from './service/question.service';

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

export class AppComponent {
  // @HostListener('window:beforeunload', ['$event'])
  // beforeunloadHandler(event:any) {
  //     alert('By refreshing this page you may lost all data.');
  // }
  title = 'Quiz';
  newdata: any;


  countryNum!: number;
  constructor(private questionService:QuestionService) { }
 
  saveCont: any = [];
  options:any=[];
  saveCap:any=[];
  

  ngOnInit() {
    this.questionService.getCountriesJson().subscribe((res: any) => {
      this.newdata = res.data;
      this.getRandomnames()
     
    })
  }

  getRandomnames(){
    for (let i = 0; i < 5; i  ) {
      let countryNum = Math.floor(Math.random() * this.newdata.length);
     
    this.saveCont.push(this.newdata[countryNum].name);
   
  
      this.saveCap.push(this.newdata[countryNum].capital)
   
    }
    for (let j = 0; j < 3 ; j  ) {
      let randomNum = Math.floor(Math.random() * this.newdata.length);
      this.options.push(this.newdata[randomNum].capital)
    }
  
  
  }
 userIndex:any=0;
 event:any
 changeIndex(number: number,event:any){
 
  if(this.userIndex>0&&number<0||this.userIndex<=this.saveCont.length && this.userIndex<=this.saveCap.length &&number>0){
    this.userIndex =number;
    // event.preventDefault();
  }



  
  }

HTML File

<h1>Quiz</h1>
<div *ngIf="saveCont && saveCap " >
    <form >
      <h1>What is the capital of{{saveCont[userIndex]}}</h1><br>
<li *ngFor="let cap of options"><button (click)="changeIndex(1,event)" id="id" >{{cap}}</button></li>
      <li ><button (click)="changeIndex(1,event)"   id="idx">{{saveCap[userIndex]}}</button></li><br> 
    

     </form>
     
      </div>

CodePudding user response:

Buttons in forms are by default of type submit. If you don't want to submit the form, but perform a custom click event, you should set the type to button like:

<button type="button" (click)="changeIndex(1,event)"   id="idx">{{saveCap[userIndex]}}</button>
  • Related