Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : Manual redirect to route

Tags:

angular

I just recently started using angular 4 instead of angular.js 1.

I have followed the heroes tutorial to learn about the fundamentals of angular 4 and I am currently using angular's own "RouterModule" from the "@angular/router" package.

In order to implement some authorization for my application I would like to know how to manually redirect to another route, I can not seem to find any useful information about this on the internet.

like image 241
Stan Hurks Avatar asked Nov 06 '17 09:11

Stan Hurks


People also ask

What is redirect in routing?

The pathMatch property, which is required for redirects, tells the router how it should match the URL provided in order to redirect to the specified route. Since pathMatch: full is provided, the router will redirect to component-one if the entire URL matches the empty path ('').

What is redirecting routes in Angular?

When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translates the initial relative URL (”) to the desired default path.

Which Angular package is used to route to URL?

Generate an application with routing enabledlink The following command uses the Angular CLI to generate a basic Angular application with an application routing module, called AppRoutingModule , which is an NgModule where you can configure your routes.


3 Answers

Angular routing : Manual navigation

First you need to import the angular router :

import {Router} from "@angular/router"

Then inject it in your component constructor :

constructor(private router: Router) { }

And finally call the .navigate method anywhere you need to "redirect" :

this.router.navigate(['/your-path'])

You can also put some parameters on your route, like user/5 :

this.router.navigate(['/user', 5])

Documentation: Angular official documentaiton

like image 200
Boulboulouboule Avatar answered Oct 09 '22 06:10

Boulboulouboule


Redirection in angularjs 4 Button for event in eg:app.home.html

<input type="button" value="clear" (click)="onSubmit()"/>

and in home.componant.ts

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

 @Component({
   selector: 'app-root',
   templateUrl: './app.home.html',
 })

 export class HomeComponant {
   title = 'Home';
   constructor(
     private router: Router,
    ) {}

  onSubmit() {
    this.router.navigate(['/doctor'])
 }
 }
like image 10
Krishnamoorthy Acharya Avatar answered Oct 09 '22 04:10

Krishnamoorthy Acharya


You should inject Router in your constructor like this;

constructor(private router: Router) { }

then you can do this anywhere you want;

this.router.navigate(['/product-list']);
like image 9
Metehan Senol Avatar answered Oct 09 '22 04:10

Metehan Senol