繁体   English   中英

如何停止页面在 angular 中单击按钮时重新加载

[英]how to stop page getting reload on button click in angular

如何停止页面在 angular 中单击按钮时重新加载。我正在 angular 中创建一个测验应用程序。我正在从 api 中获取随机问题和选项。在选择选项时,下一个问题即将到来,因为我想实现此功能。但随着它页面也重新加载我不想要的。如何停止这个

文件

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>

forms 中的按钮默认为submit类型。 如果你不想提交表单,而是执行自定义点击事件,你应该将类型设置为button ,如:

<button type="button" (click)="changeIndex(1,event)"  class="btn btn-primary btn-block btn-lg" id="idx">{{saveCap[userIndex]}}</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM