Using router.navigate in an Angular 2 application does not function properly if it is called from a button element

This is a component I have created:

@Component({
    selector: 'login-view',
    templateUrl: 'app/login/login.component.html',
    directives: [MATERIAL_DIRECTIVES, FORM_DIRECTIVES]
})
export class LoginComponent implements OnInit{

    loginForm: ControlGroup;

    constructor(
        private _formBuilder: FormBuilder, private _router: Router) {
    }

    ngOnInit() {
        // some initialization
    }

    submitLoginForm(){
        // implementation pending
    }

    goToRegister(){
        this._router.navigate(['/Register']);
    }

    goToResetPassword(){
        this._router.navigate(['/ResetPassword']);
    }
}

This is the template for the component above:

<form [ngFormModel]="loginForm" (ngSubmit)="submitLoginForm()">

    <input md-input ngControl="mobileNumber" type="number" id="mobileNumber">

    <input md-input type="password" ngControl="password" id="password"/>

    <button md-raised-button type="submit" class="md-raised md-primary">Login</button>

    <div>
        // These Work
        <a md-button class="md-primary" (click)="goToResetPassword()">Forgot password?</a>
        <a md-button class="md-primary" (click)="goToRegister()">New here? Register</a>

       //These don't work, reloads the app
       <button md-button class="md-primary" (click)="goToResetPassword()">Forgot password?</button>
       <button md-button class="md-primary" (click)="goToRegister()">New here? Register</button>
    </div>
</form>

When calling goToResetPassword() or goToRegister() from the (click) event of <a>, it works correctly.

However, if I change the html element to <button>, it simply reloads the entire app without displaying any errors in the console.

Answer №1

Another option that could be effective

 (click)="executeResetPassword();false"

in order to stop the button from submitting by default.

Answer №2

Give this a try, it might be the solution you're looking for: -

   <a type="button" class="btn "              
   [routerLink]="['/Bar']">{{labels.CancelBtnText}}</a>

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

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Exploring the benefits of leveraging TypeScript with AWS NodeJS for improved stacktrace visibility over traditional JavaScript

I'm contemplating the idea of transitioning my existing JavaScript codebase to incorporate TypeScript in NodeJS. One aspect that I am concerned about is being able to view the stack trace in AWS CloudWatch (request log) in case an error occurs during ...

Ensure to verify the slot for any included content to see if it is vacant

I'm currently facing a dilemma without a clear solution in sight. I have created some custom components that utilize content projection and multi slot transclusion. For instance, I have a Card (Bootstrap) and I want to customize elements like the he ...

Are there any methods to incorporate Facebook and Google login into an Ionic progressive web app (PWA)?

After successfully developing an app in Ionic 3 for Android and iOS, I encountered a problem when adding the browser platform. The Facebook and Google login features were not functioning as expected. Despite the assurance from Ionic documentation that the ...

Tips for implementing a coupon code feature on Stripe checkout in an Angular 8+ application

I need to implement an input option for entering coupons in the Stripe payment gateway when the handler is open on the front end. I currently have a Stripe window open and would like to provide users with a way to enter coupon codes. // Function to Load ...

Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array. Here is the initial array of objects: "attentionSchedules": [ { "room": "1", ...

Is there a way to dynamically exclude files from the TypeScript compiler?

Currently, I am in the process of setting up a node/typescript server for a real-time application. Both my server and client are located within the same folder. My goal is to exclude "src/client" from the typescript compiler when executing the "server:dev ...

Steps for running an Angular application in IntelliJ:1. Open IntelliJ IDEA

I'm currently navigating through IntelliJ to set up Angular support. https://www.jetbrains.com/help/idea/2017.1/using-angular.html#install_angular_cli After successfully creating the project, I am unsure of how to run it. My guess is that I need to ...

I'm experiencing unexpected behavior with the use of Mat-Spinner combined with async in Angular 12, particularly when using the rxjs function

I am relatively new to rxjs and it's possible that I'm using the wrong function altogether. Currently, I'm working on a .NET Core 3.1 backend and implementing a two-second delay for testing purposes. I have a service call that I need to mock ...

Guide to modifying text color in a disabled Material-UI TextField | Material-UI version 5

How can I change the font color of a disabled MUI TextField to black for better visibility? See below for the code snippet: <TextField fullWidth variant="standard" size="small" id="id" name=&quo ...

Encountered an ERROR when attempting to deploy a next.js app to Azure Static Webapp using GitHub actions for

I am encountering an issue that is causing some frustration. The problem only arises during my github actions build. Interestingly, when I run the build locally, everything works perfectly and I can access the route handler without any issues. However, eve ...

What is the process for changing the src property to a URL that is outside of the project

Currently, I am developing a project using Ionic. My goal is to include a variable that holds the URL of an image in an image tag. <div *ngFor="let item of imagearr"> <img [src]="item.image.URL"> Unfortunately, when I attempted this method, i ...

What is the hierarchy of importance for routes in Angular - parent versus child levels?

Let's say I define a top-level route with the path '/some/childr': [{ path: '/some/childr'}] Then, I create another top-level route /some with a child route /childr: [{ path: '/some', children: ['/childr']}] ...

What steps can be taken to choose an Angular npm package for datetimepicker in a TypeScript file?

I am facing an issue where document.getElementById and document.querySelector are not returning any results ... I need to access this specific HTML element in order to set a new attribute at a certain event. <datetime id="datePicker" [datepicker]="da ...

Testing specific components within an Angular 2 folder using unit tests

Our current project scenario involves: Implementing new UI changes in the project. Updating test cases for components with outdated UI test cases. Due to the presence of old UI test cases in all components, they are failing simultaneously, making it diff ...

What is the best way to utilize switchMap in order to terminate ongoing http requests and only receive the latest subscription?

To cancel a pending HTTP request, I attempted using `subscription.unsubscribe` in this manner: getAgentList(pageNumber: number, filter: string): any { let requestUrl: string = 'api/service/agents_search?ACCT=' +this.accountId; if ( this. ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

Guide on invoking an API with a private IP on an EC2 instance

I successfully deployed an Angular app and a Java REST-API on my ec2-instance. When accessing the Java REST-API via the public IP in my Angular app, everything works fine. However, if I try to use the private IP of my instance, it results in a connection ...

Guidelines on utilizing map varieties for creating a type definition for `Object.keys`

Exploring a stricter definition of the Object.keys function using mapped types in TypeScript. An Illustrative Example: To begin, consider an object defined using const: const myObj = { a: 'some value', b: 5 }; Typically, when utilizing Ob ...