Guide on navigating to a different page using a function with router link in Angular using TypeScript

Trying my hand at Angualar and Typescript for the first time. I am working on creating a login page where users can move to another page if their credentials are correct. To achieve this, I want to use a function that is triggered by clicking a button. However, my current implementation doesn't seem to be working as expected.

Here is a snippet of my code:

<button type="submit" id="btnLog" (click)="log(userName.value , password.value )" routerLink="/home" >

In app.component.ts file:

log(uName , uPass) {
   //Validation Part

    if((name==uName) && (pass==uPass)){
      attrInvalid.innerHTML="routerLink=/\"home\""
    }else{
      attrInvalid.innerHTML="Invalid UserName or Password"
    }
  }

Answer ā„–1

Utilize the router.navigate method to move to a specific route upon successful validation. It is recommended to avoid direct DOM manipulation (such as using innerText) when working with Angular.

To begin, inject an instance of the Router class in the constructor of your component class like so:

error:Boolean = false;
constructor(private router: Router) { }

Then, within your log method, make use of it:

log(uName , uPass) {
   //Validation Part

    if((name==uName) && (pass==uPass)){
      this.router.navigate['/home'];
    }else{
      //handle the error to show the error message using *ngIf
       this.error = true;
    }
  }

Additionally, remember to adjust the button HTML:

<button type="submit" id="btnLog" (click)="log(userName.value , password.value )" >
<span *ngIf="error" id="attrInvalid">Login failed</span>

Answer ā„–2

The response provided above is nearly correct but may not be entirely accurate for Angular version 14.02.

A cleaner approach would be to utilize the router object directly in order to eliminate the need for a separate variable:

<button type="submit" id="btnLog" (click)="log(userName.value , password.value )" >

In the .ts file, it is essential to import and inject the router before setting up the desired route:

import { Router } from '@angular/router';

[...]

  constructor(private router: Router) { }

  log(uName , uPass) {
    //Validation Part

    if((name==uName) && (pass==uPass)){
      this.router.navigate(['/home']);
    }else{
      alert("Invalid UserName or Password");
    }
  }

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

Exploring ways to test the ng-web-apis/geolocation Observable within an Angular 8 environment

I'm currently working on testing a basic Angular 8 service that utilizes the GeoLocation Service from Web APIs for Angular, which can be found at this link. public enableGPS() { if (!this.locationSubscription) this.locationSubscription = ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

What is the process for setting up a Quill Editor within an Angular 2 Component?

I am currently working on creating my own Quill editor component for my Angular 2 project. To integrate Quill into my project, I utilized npm for installation. My goal is to develop a word counter application using this component and I am referring to the ...

The InAppPurchase Plugin in Cordova is throwing the error message "Encountered an error: Cannot access the 'getProducts' property as it is undefined."

Currently, I am utilizing the cordova in-app-purchase plugin for my application. However, I am encountering an error that reads "ERROR TypeError: Cannot read property 'getProducts' of undefined" The .ts file appears as follows: window['plu ...

Update the form field with today's date in a JHipster application

In our current project in JHipster, we are facing a challenge with setting the default value of a form field as the current date. JHipster offers a moment format for dates, which is essentially an ngbdatepicker. However, when attempting to change the inpu ...

Angular 2 TypeScript: How to effectively sort an array

Iā€™m currently exploring how to implement array filtering in Angular 2 with TypeScript. Specifically, I am trying to filter data for a search bar in Ionic 2. While the list in the template successfully displays the data, I am encountering difficulty getti ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

activate the change detection for a specific subcomponent

Let's say I am conducting a test on MyComponent, which has a template that includes SubComponent The structure of MyComponent is as follows @Component({ selector: 'my-component', template: ` <sub-component [input]="property"> ...

Improve the efficiency of importing Bootstrap SCSS files

I am working on an Angular4 CLI project with Universal SSR. Within my own SCSS file, I am importing Bootstrap like so: @import '../node_modules/bootstrap/scss/bootstrap'; Bootstrap itself imports numerous other SCSS files, such as: @import "tr ...

Troubleshooting challenges with setting up Nginx Reverse Proxy, ExpressJS, Angular, and SSL configurations

Being relatively new to this subject, I found myself with a few unanswered questions despite my efforts to search through Google. Here's what I understand so far - nginx functions as my webserver, responding to incoming requests by serving my client ...

Error: Model function not defined as a constructor in TypeScript, mongoose, and express

Can anyone help me with this error message "TypeError: PartyModel is not a constructor"? I've tried some solutions, but now I'm getting another error as well. After using const { ... } = require("./model/..."), I'm seeing "TypeError: C ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Ideal method of re-entering ngZone following an EventEmitter event

There is a specific component that wraps around a library, and to prevent the chaos of change detection caused by event listeners in this library, the library is kept outside the Angular zone: @Component({ ... }) export class TestComponent { @Output() ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

The unspecified value of a dynamically generated button

Currently, I am working on generating ion cards with a response. Each ion-card contains 3 buttons. I am able to receive the response properly, but I am facing an issue with assigning values to the buttons, or possibly implementing it incorrectly. Here is ...

Error: 'ngForOf' is not recognized as a valid property of the 'tr' element

Since this afternoon, I've been facing a challenge that I can't seem to grasp. The issue lies within a service I created; in this file, there is an object from which I aim to showcase the data in a loop. An error message is displayed: NG0303: C ...

Ways to enlarge image size without compromising the image resolution?

My image is in PNG format or as a blob. It has dimensions of 800px by 600px. However, when I try to resize it using various canvas methods like the one mentioned in this Stack Overflow thread: Resize image, need a good library, it loses quality. I wou ...

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

Using Typescript to extract/calculate types with limitations without the need to explicitly extend or broaden them

I have a function called build that constructs a User object using the provided parameters. I want to define the function in such a way that it recognizes which parameters are being passed and incorporates them into the return value. Initially, I thought ...