1

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 " class="quescard">
    <form >
      <h1>What is the capital of{{saveCont[userIndex]}}</h1><br>
<li *ngFor="let cap of options"><button (click)="changeIndex(1,event)" id="id" class="btn btn-primary btn-block btn-lg">{{cap}}</button></li>
      <li ><button (click)="changeIndex(1,event)"  class="btn btn-primary btn-block btn-lg" id="idx">{{saveCap[userIndex]}}</button></li><br> 
    

     </form>
     
      </div>

1 Answer 1

4

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)"  class="btn btn-primary btn-block btn-lg" id="idx">{{saveCap[userIndex]}}</button>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.