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

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

The datatype 'string' cannot be assigned to the datatype '(token: string) => void'

Within my Angular2 application, I have a class that includes several properties which will be assigned values within components. @Injectable() export class Globals { private token: string; private authorization: string; private roleUser: boole ...

Create a custom data structure resembling a record, where certain keys are assigned specific value types

My objective is to establish a custom type resembling a record, where certain keys are designated for specific value types. The proposed object would look something like this: const o: TRec = { text: "abc", width: 123, height: 456, //...an ...

Looking to build a unique form validator for two inputs? Ensure that one input number is consistently larger than the other with this guide

Is it possible to create a custom form validator with 2 inputs? My goal is to ensure that one input number is always greater than the other. ValidateMaxMin(control: FormControl) { console.log(control.value.productMin); if (control.value.productM ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

Having difficulties in accessing an API with Ionic 3

Whenever I attempt to connect with an API, I keep encountering the Cross-Origin Read Blocking (CORB) blocked cross-origin response error. Can anyone provide guidance on how to resolve this issue? Any assistance would be greatly appreciated. ...

Struggling with integrating Axios with Vue3

Can someone assist me in figuring out what is going wrong with my Axios and Vue3 implementation? The code I have makes an external call to retrieve the host IP Address of the machine it's running on... <template> <div id="app"> ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Issues with the Angular Global Messaging service and how to tackle them

I am currently developing a web application using Angular 7 and I have implemented an API interceptor to show alerts when errors occur. Everything was working fine until I added a messaging service and messaging component. When I tried pushing the error me ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

Learn the steps for implementing i18n-x in Angular 2 to localize constant property values

I am currently working on localizing my Angular2 application using the i18n-x form from here. It has been successful for attributes like so: <p-dialog i18n-header header="User Details"></p-dialog> The result is: <trans-unit id="fe871da89f ...

I'm eager to showcase live, incoming data on the chart. However, I'm feeling a bit lost on how to proceed. Can you help

I am currently utilizing the line chart feature of ng2-charts in my Angular project. However, I am unsure how to create a graph with real-time data. Here is an example of some sample data being used for the line chart: lineChartData: ChartDataSets[] = [ { ...

Having trouble with 'npm <script-command>' not working? Try changing it to 'npm run-script <script-command>' instead

Currently, I am configuring a node js backend to operate on TS for the first time within a mono-repo that has a specific folder structure. You can view the structure here. The package.json file is located in the main directory as shown below: "scr ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

Exploring Angular: Enhancing Routing through GET Requests

I've been working on a cutting-edge application that combines an Angular 2 frontend with a powerful Java backend. An exciting feature of this application is a dynamic form, consisting of various search criteria. Upon submission, I execute an http get ...

Tips for improving the performance of your Ionic 2 app

Recently, I've been working on enhancing the performance of my Ionic 2 App, particularly focusing on optimizing page loading speed. After closely analyzing the timeline of page transitions using Chrome Dev Tools, it became evident that the bottleneck ...

Troubleshooting issue of incorporating hintText in a TextField within a create-react-app-with-typescript

After recently downloading, installing, and running the create-react-app-with-typescript, I have been exploring different components. My latest experiment involved adding a TextField with hintText using the following code: import TextField from 'mate ...

Different ESLint configurations for mjs, js, and ts files

For my project, I've set up ESM (.mjs) files for server-side code, CommonJS (.js) for tooling, and TypeScript (.ts) for the client side. In VS Code, when I look at CommonJS files, I'm getting errors related to requires such as "Require statement ...

A guide on automatically focusing on a Material UI Formik form TextField using React and TypeScript

I'm attempting to automatically focus my textField, but the 'autoFocus' attribute only seems to work after I submit the form and add a value. If no values are added (i.e. when opening the miui modal for the first time), the autoFocus does no ...