Guide to navigate to a different component in Angular 8 once conditions have been verified

Recently delving into Angular 8, I find myself crafting a login component with the intention of redirecting to another component upon entering the correct username and password. Here's what my code looks like so far:

Here is the TypeScript for my login component:

       import { Component, OnInit } from '@angular/core';
       import{FormGroup,FormBuilder,Validators} from '@angular/forms'


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  myForm:FormGroup
  submitted=false;
  _baseURL : string;
  formvalid: boolean;
   user:string;
   pwd:string;
  constructor(private formbuilder:FormBuilder){}


  ngOnInit(){
    this.myForm = this.formbuilder.group({
    username:['',Validators.required],
    password:['',[Validators.required,Validators.pattern("^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$")]]
    });
    this._baseURL="";
    this.formvalid=false;
  }

  Submitme(){
    this.submitted = true;

    if (this.myForm.invalid) {
      this.formvalid=false;
        return;
    }
    if (this.myForm.valid) {
      this.formvalid=true;
    this._baseURL= 'Welcome'+" "+ this.myForm.controls.username.value;
  }
  this.user=this.myForm.controls.username.value;
  this.pwd=this.myForm.controls.password.value;
}
rest(){
  this.myForm.reset();
  this.submitted = false;
}
}

And here is the HTML for my login component:

        <h1 class="text-center" [hidden]="formvalid">Login</h1>
          <form [formGroup]="myForm" (ngSubmit)="Submitme()" class="text-center">
           <div class="container bg-dark" [hidden]="formvalid" style="border: 1px solid black;">
         <div class="row mt-3">
           <div class="col-lg-5">
         <label for="name" class="text-white">Username :</label>
         </div>
         <input type="text" formControlName="username" class="col-lg-4 form-control"
           [ngClass]="{ 'is-invalid': submitted &amp;&amp; myForm.controls.username.errors }">
          <div *ngIf="submitted &amp;&amp; myForm.controls.username.errors" class="text-danger">
            <div *ngIf="myForm.controls.username.errors.required">First Name is required</div>
        </div>
       </div>
     <div class="row mt-2">
           <div class="col-lg-5">
       <label for="pwd" class="text-white">Password :</label>
         </div>
      <input type="password" formControlName="password" class="col-lg-4 form-control"
      [ngClass]="{ 'is-invalid': submitted &amp;&amp; myForm.controls.password.errors }">
       <div *ngIf="submitted &amp;&amp; myForm.controls.password.errors" class="text-danger">
     <div *ngIf="myForm.controls.password.errors.required">password is required</div>
      <div *ngIf="myForm.controls.password.errors.pattern">Pwd must contain atleast one upper and 
    lower case character one special character one digit and 8 characters in length  </div>
   </div>
    </div>
     <button class="btn btn-primary mt-2 mb-3" type="submit" 
   [routerLink]="'/afterlog'">Submit</button>&nbsp;
     <input type="button" (click)="rest()" value="Reset" class="btn btn-primary mt-2 mb-3">
 </div>
      </form>

Upon successful login, the goal is to navigate to another component displaying a welcome message through Angular 8 routing mechanisms. Appreciate any assistance!

Answer №1

Create routes within your module file (for example, app.module):

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
];

@NgModule({
   imports: [
    RouterModule.forRoot(appRoutes)
  ],
  ...
})

In your login component:

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

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

Submitme() {
  ...
  this._router.navigateByUrl('/welcome');  // navigate to welcome component
}

For more information, visit this link.

Answer №2

It seems like you are trying to navigate to a new component and pass along some data to display a welcome message there. One way to achieve this is by using queryParams to send your username as a parameter to the welcome component. Alternatively, you can also store the logged-in user in localStorage instead of sending it as a query parameter.

this.router.navigate(['/welcome'], { queryParams: { username: this.myForm.controls.username.value} });

You can then retrieve and use the username in your welcome.component.ts file:

username: string;
constructor(private route: ActivatedRoute) {
    this.username = this.route.snapshot.paramMap.get('username');
}

In your welcome.component.html file, you can display the welcome message with the username:

<div>Welcome {{username}}!</div>

Answer №3

If my understanding is correct, you are looking to redirect to a new page after the form submission?

To achieve this, start by injecting the Router class into your constructor. Include this line in your constructor: private router: Router

Don't forget to import the Router with this line:

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

Now you can utilize the Router class in your TypeScript file.

To navigate to another page, use this snippet: this.router.navigate(['/']); In the example above, it would navigate to the home page.

You can also navigate relative to a specific path like so: Simply add this line to your constructor: private route: ActivatedRoute Ensure you import ActivatedRoute Then you can navigate relative to the current route using this code:

this.router.navigate(['../../'], { relativeTo: this.route });

This.route refers to the ActivatedRoute reference.

For more information on routing and navigation, visit: https://angular.io/guide/router

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

Getting Started with Angular 2 Installation

Looking for a straightforward way to incorporate Angular2 into a single HTML file without using Bower, NPM, NuGet, or other complex methods? EDIT: Thanks to Dieuhd's suggestion, I was able to make Angular 2.0 work using the following script referenc ...

Strategies for managing various errors that can arise when multiple Angular components are subscribed to a single state

My Angular application is facing a dilemma with three components at play: Component #1: Shows a list of items Component #2: Displays recently used items Component #3: Exhibits the current item For now, let's assume they're all visible on the sa ...

How to conceal parameters in Angular URL?

Within the modeling-agency component, there is a button that routes to editModelingAgency/{{element.userid}}. Currently, clicking on this button takes the user to a specific route with a link like /base/editModelingAgency/15, but I want to show the link as ...

Angular 7 data update causing issues with Bootstrap carousel functionality

I am encountering an issue with the Bootstrap carousel in my Angular 7 application. The carousel contains data that needs to be updated at regular intervals. Initially, the carousel works as expected. However, once the HTTP service updates the array of sli ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

Verify if the transaction is present in rxjs

private transactions = new BehaviorSubject([]); getTransactions(): Observable<ITransaction[]> { return this.transactions.asObservable(); } checkTransactionsExist():Observable<boolean> { return this.getTransactions().pipe ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

The Angular 2 update I posted successfully refreshes my list, however, it does not reflect any changes in

My current project involves using Angular2 and MVC. While I've been following tutorials on angular.io, I've made some adjustments to tailor the solution to my needs. One of the main components is a table that displays clients along with their ide ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

What is the best way to increase the size of an array and populate it with just one specific element in Types

If I want to create an array in Python, like [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], all I have to do is use [1] * 10. >>> [1] * 10 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Is it possible to achieve the same result in TypeScript? ...

Encountering an error while trying to implement strong typing in a function on a Node API service: 'Unexpected token ":"'

I've developed a TypeScript Node API service and here's a snippet of my code: class dataStreamConfig { constructor() { } conclaveObj = (firstParam: string, secondParam: number, thirdParam: any): any => { //my ...

Converting an existing array into a TypeScript string literal type: A step-by-step guide

Converting TypeScript Arrays to String Literal Types delves into the creation of a string literal type from an array. The question raised is whether it's feasible to derive a string literal from an existing array. Using the same example: const furnit ...

Introducing the concept of type-specific name inclusion

I am currently developing my Angular app using TypeScript with the goal of preventing redundancy through some form of generic handling. Here is where I am starting: class BaseProvider { api_url = 'http://localhost:80/api/FILL_OUT_PATH/:id&apo ...

Develop a fresh Typescript-driven sql.js database

I'm in the process of converting my JavaScript code to TypeScript. One of the libraries I rely on is sql.js. I have successfully installed the corresponding typing for it, but I am facing a roadblock when it comes to creating the database. Here is ho ...