Open In App

How to force redirect to a particular route in angular?

Last Updated : 15 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction:

We can use the property binding concept and we can pass query parameters to routerLink. Using Property binding we can bind queryParams property and can provide the required details in object.

Property Binding: It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) element.




import {Component, OnInit} from '@angular/core'
   
@Component({
   
selector:'app-property',
template:
`<p [textContent]="title"></p> 
`
})
   
export class AppComponent implements OnInit{
   
constructor(){}
ngOnInit() {}
   
title='Property Binding example in GeeksforGeeks';
   
}


Output:

We can implement the route re-direction in two ways:
1) The first method is by doing from .html file.
2) The second method is from the .ts file.

Syntax for .html file:
 




<a [routerLink]="[/path]" >
   State Details 
</a>


    • Approach:

    • First, configure the routes in app.module.ts
    • Implement routerLink property binding with the required path in HTML file.
    • After mentioning the above instructions, then we can click on the configured HTML element and can redirect it.
    • Once you are done with clicking it it will automatically redirect you to another component.

    Implementation by code:
    app.module.ts:




    import { NgModule } from "@angular/core";
    import { BrowserModule } from "@angular/platform-browser";
    import { RouterModule, Routes } from "@angular/router";
      
    import { AppComponent } from "./app.component";
    import { StateComponent } from "./state/state.component";
      
    const routes: Routes = 
      [{ path: "punjab", component: StateComponent }];
      
    @NgModule({
        imports: [BrowserModule, RouterModule.forRoot(routes)],
        declarations: [AppComponent, StateComponent],
        bootstrap: [AppComponent],
    })
    export class AppModule {}

    
    

    app.component.html:




    <a [routerLink]="['/punjab']">
       State Details 
    </a>
    <router-outlet></router-outlet>

    
    

    After clicking on the anchor tag, then we can see that the url will be changed in the following way and we will be directed to the configured component in the app.module.ts file.

    Output:
    state.component.html:
     

  • Second method from .ts file:

      Approach:

    • First, configure the routes in app.module.ts
    • Implement routing by importing ‘Router’ from ‘@angular/router’.
    • Then initialize the router in the constructor.
    • After doing the above process, then implement routing in a function so that the function can be triggered from .html file.
    • Once everything is done then we can force redirect the route to another component.

    Implementation By code:
    app.module.ts:




    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { RouterModule, Routes } from '@angular/router';
       
    import { AppComponent } from './app.component';
    import { StateComponent } from './state/state.component';
       
    const routes: Routes = [
      { path: 'punjab', component: StateComponent },
    ];
       
    @NgModule({
      imports:      [ BrowserModule, RouterModule.forRoot(routes) ],
      declarations: [ AppComponent, StateComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

    
    

    app.component.ts:




    import { Component, OnInit } from '@angular/core';
    import {Router} from '@angular/router';
      
      
    @Component({
      selector: 'app-main',
      templateUrl: './main.component.html',
      styleUrls: ['./main.component.css']
    })
    export class HomeComponent implements OnInit {
      
      constructor(private router:Router) { }
       
     ngOnInit(){}
     onSelect(){
          this.router.navigate(['/punjab']);
     }
    }

    
    

    app.component.html:




    <a (click)="onSelect()">
       State Details 
    </a>
    <router-outlet></router-outlet>

    
    

    After following the above code and one if you click on the anchor tag then the url will be changed and you will be redirected to the respective configured component.

    Output:



Similar Reads

How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?
HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user's browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user's browser to the server. Having a site in HTT
3 min read
How to redirect to a particular section of a page using HTML or jQuery?
Redirection will take the user to the desired page or section of the website that the user wants to visit. We will do it using HTML and jQuery differently. Let us take a look at the practical implementations. Table of Content Using HTMLUsing JQueryMethod 1: Using HTMLOne can use the anchor tag to redirect to a particular section on the same page. Y
3 min read
Laravel | Route::resource vs Route::controller
In Laravel, the Route actions can be controlled by any of the following two methods, either by using Route::resource method or by using Route::controller method. But both of them have their differences. Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easi
2 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g
4 min read
How to send PDF in express route response and force browser download ?
In this article, we will see how to send PDF files in the express route's response and make the browser force download the file. Approach:Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to download PDF.Execute ajax call on button click to GET
4 min read
How to Redirect Users to Last Active Page before Logout in Angular ?
Redirecting the users to the last active page before logout after they log in is the most common feature or functionality in web applications. This functionality enhances the user's experience by saving their session state and also enables them to resume their activities seamlessly after they log in. In the article, we will see the practical implem
7 min read
Angular Authentication Using Route Guards
In Angular, implementing authentication is important for securing routes and controlling access to different parts of the application based on user authentication status. Angular provides a powerful feature called Route Guards, and among them, the Auth Guard is used to control navigation based on the user's authentication state. In this article, we
12 min read
How to Handle Route Parameters in Angular?
In Angular, routing plays an important role in building single-page applications (SPAs). Often, you need to pass data between components through the URL using route parameters. Route parameters allow you to define dynamic segments in your routes, which can be extracted and used in your components. This article will explore how to handle route param
3 min read
Angular PrimeNG Form AutoComplete Force Selection Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use TreeTable Column Resize in Angular PrimeNG. Form AutoComplete Force Selection Component: It is used to validate t
17 min read
JavaScript | Redirect a URL
Prerequisites: Learn Basic HTML Learn Basic Javascript Redirecting a URL in JavaScript is nothing but sending the user from a URL to another URL. In Javascript, window.location function is used to redirect to a URL. JavaScript codes for redirecting to a URL: Code #1: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Redirect url in Javas
2 min read