Preventing Page Refresh when Button is Clicked in Angular

How can I prevent page reload when a button is clicked in Angular? I'm developing a quiz application in Angular where I fetch random questions and options from an API. When users select an option, the next question should appear without reloading the page. How can I achieve this functionality without the page reloading?

Typescript 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 {
  
  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;
    }
  }

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>

Answer №1

Forms usually have buttons that automatically submit the form when clicked. However, if you want a button to trigger a custom event instead of submitting the form, you need to specify the type as button. This can be done like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...

Acquiring the value of an input box in VBA through HTML

Can someone provide guidance on how to retrieve the value from an input box on an Internet Explorer page using VBA? I have tried various solutions but none seem to work. Below is the HTML code I am working with. I specifically need the value of the bolded ...

Issue with Angular ngFor binding. What could be causing this error to occur?

I have a main component called DOCUMENT. This document receives a URL segment and retrieves an array of associated objects from my database. Then, using @Output() documents = new EventEmitter() and an @Input() in a DOCUMENT VIEW component, I loop through t ...

unable to apply angular measurement inside quotation marks

What is the reason for this issue: <ul class="dropdown-menu"> <li ng-repeat="choice in dropDownItems"> <a class="btn" ng-click="mnuClick('{{choice}}')">{{choice}}</a> </li> </ul> However, this code wo ...

Initially, when an iframe is loaded in Angular 10, it may display a 404 error page

Hey there! I'm currently using the HTML code below to incorporate an iframe and display an external page hosted on the same domain so no need to worry about cross domain issues: <iframe frameborder="0" [src]="url"></iframe ...

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

Images that are see-through or translucent

Can someone confirm if Internet Explorer supports transparent PNGs now? How about Chrome? ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

What is preventing me from passing a JSON array as data in a GET request using jQuery Ajax?

When sending a get request like the one below: $.ajax({ url: 'http://localhost:8000/api/points/', contentType:"application/json", dataType: "json", data: JSON.stringify({"content_type":content_type,"object_id":object_id}), t ...

Include a personalized header in $http

In my factory, I have multiple functions that follow this structure: doFunction: function () { return $http({ method: 'POST', url: 'https://localhost:8000/test', data: {}, headers: { "My_Header" ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...

Location of chat icon in Dialogflow messenger

After successfully embedding the Dialogflow messenger in my website, I noticed that in mobile view, the chat icon is blocking the bottom navigation bar. You can refer to the screenshot here. Is there a way to reposition the chat icon higher on the page? I ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

Is there a way to verify the existence of an Array Field?

For JavaScript, the code would look like this: if (array[x] != undefined && array[x][y] != undefined) { array[x][y] = "foo"; } Is there an equivalent simple method for achieving this in Java? I have tried checking if the field is null or no ...

Is there a way to have a page automatically send you to a different URL depending on the information included in the link's GET statement?

I am in need of a straightforward piece of code that can automatically redirect a user to a different URL specified within the current URL: For instance: http://example.com/index.php?URL=anothersite The scenario is as follows: a user first lands on http ...

Creating a CSS Box Along the Border of Another Box: A Step-by-Step Guide

Is there a way to render a box on another box's border, similar to the example image here: Expected Output I attempted using flexbox to achieve this, but unfortunately wasn't successful in finding a solution. If you have any advice or suggestio ...

Ways to enable a user to edit a calculated property in VueJS?

I am currently working on collecting data that the user can download, and I am facing a challenge in determining the best way to handle the filename. To ensure the default filename is dynamic and based on the current date, I believe creating a computed pro ...

What could be the reason for the "begin" script failing to execute?

I have a simple node and express application that works as expected, but I encounter an issue when trying to run the server from the script. When my script is set to "start", running the command simply opens my cmd. However, if my script is set to any oth ...

Unable to locate Node.js /socket.io/socket.io.js on express 4.0

Currently, I am working on implementing a chat feature on my website. During testing on my local server, everything was running smoothly as port 8080 on localhost was readily available. However, after deploying my code to Heroku, I encountered an issue whe ...