Questions tagged [angular-routing]

The ngRoute module provides routing and deeplinking services and directives for AngularJS apps.

AngularJS routes enable you to create different URLs for different content in your application. Having different URLs for different content enables the user to bookmark URLs to specific content, and send those URLs to friends etc. In AngularJS each such bookmarkable URL is called a route.

AngularJS routes enables you to show different content depending on what route is chosen. A route is specified in the URL after the # sign. Thus, the following URL's all point to the same AngularJS application, but each point to different routes:

 http://myangularjsapp.com/index.html#books
 http://myangularjsapp.com/index.html#albums
 http://myangularjsapp.com/index.html#games
 http://myangularjsapp.com/index.html#apps

When the browser loads these links, the same AngularJS application will be loaded (located at http://myangularjsapp.com/index.html), but AngularJS will look at the route (the part of the URL after the #) and decide what HTML template to show.

At this point it may sound a little abstract, so let us look at a fully working AngularJS route example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1">Route 1</a><br/>
<a href="#/route2">Route 2</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

    module.controller("RouteController", function($scope) {

    })
</script>

Each part of this sample application will be explained in the following sections.

Including the AngularJS Route Module

The first thing to notice in the example application above is the extra JavaScript included inside the head section:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

The AngularJS Route module is contained in its own JavaScript file. To use it we must include in our AngularJS application.

Declaring a Dependency on the AngularJS Route Module

The second thing to notice is that the applications's AngularJS module (called sampleApp) declares a dependency on the AngularJS route module:

var module = angular.module("sampleApp", ['ngRoute']);

The application's module needs to declare this dependency in order to use the ngRoute module. This is explained in more detail in my modularization and dependency injection tutorial, in the section about dependencies-between-modules.

The ngView Directive

The third thing to notice in the example above is the use of the ngView directive:

<div ng-view></div>

Inside the div with the ngView directive (can also be written ng-view) the HTML template specific to the given route will be displayed.

Configuring the $routeProvider

The fourth thing to notice in the example shown at the beginning of this text is the configuration of the $routeProvider. The $routeProvider is what creates the $route service. By configuring the $routeProvider before the $route service is created we can set what routes should result in what HTML templates being displayed.

Here is the code from the example:

<script>
    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);
</script>

The $routeProvider is configured in the module's config() function. We pass a configuration function to the module's config() function which takes the $routeProvider as parameter. Inside this function we can now configure the $routeProvider.

The $routeProvider is configured via calls to the when() and otherwise() functions.

The when() function takes a route path and a JavaScript object as parameters.

The route path is matched against the part of the URL after the # when the application is loaded. As you can see, the two route paths passed to the two when() function calls match the two route paths in the href attribute of the links in the same example.

The JavaScript object contains two properties named templateUrl and controller. The templateUrl property tells which HTML template AngularJS should load and display inside the div with the ngView directive. The controller property tells which of your controller functions that should be used with the HTML template.

The otherwise() function takes a JavaScript object. This JavaScript object tells AngularJS what it should do if no route paths matches the given URL. In the example above the browser is redirected to the same URL with #/ as route path.

Links to Routes

The final thing to notice in this example is the two links in the HTML page:

<a href="#/route1">Route 1</a><br/>
<a href="#/route2">Route 2</a><br/>

Notice how the part of the URLs after the # matches the routes configured on the $routeProvider.

When one of these links is clicked, the URL in the browser window changes, and the div with the ngView directive will show the HTML template matching the route path.

Route Parameters

You can embed parameters into the route path. Here is an AngularJS route path parameter example:

#/books/12345

This is a URL with a route path in. In fact it pretty much consists of just the route path. The parameter part is the 12345 which is the specific id of the book the URL points to.

AngularJS can extract values from the route path if we define parameters in the route paths when we configure the $routeProvider. Here is the example $routeProvider from earlier, but with parameters inserted into the route paths:

<script>
    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1/:param', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2/:param', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);
</script>

Both of the URLs in the when() calls now define a parameter. It is the part starting from the colon (:param)

AngularJS will now extract from the URL (route path) whatever comes after the #/route1/ part. Thus, from this URL:

#/route1/12345

The value 12345 will be extracted as parameter.

Your controller functions can get access to route parameters via the AngularJS $routeParams service like this:

module.controller("RouteController", function($scope, $routeParams) {
    $scope.param = $routeParams.param;
})

Notice how the controller function takes the $routeParams service as parameter, and then copies the parameter named param into the $scope.param property. Now your AngularJS views can get access to it, or you can use it in AJAX calls etc.

Here is a full AngularJS route parameter example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1/abcd">Route 1 + param</a><br/>
<a href="#/route2/1234">Route 2 + param</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                    when('/route1/:param', {
                        templateUrl: 'angular-route-template-1.jsp',
                        controller: 'RouteController'
                    }).
                    when('/route2/:param', {
                        templateUrl: 'angular-route-template-2.jsp',
                        controller: 'RouteController'
                    }).
                    otherwise({
                        redirectTo: '/'
                    });
        }]);

    module.controller("RouteController", function($scope, $routeParams) {
        $scope.param = $routeParams.param;
    })
</script>
</body>
</html>   
3648 questions
1
vote
2 answers

Angular 5 & .NET Core 2.0 - router navigate freeze website

I am learning Angular 5 and implementing simple application (on back-end side I am using .net core 2.0 web api). After user clicks delete button on modal I am trying to make redirection to home page, and redirection is being made but whole page…
tzm
  • 588
  • 1
  • 12
  • 27
1
vote
1 answer

Value gets lost after routing in Angular5

I am trying to get a value from the browser in forms.component.ts and use it in student.component.ts and but i loose the value after routing to student component , i have even tried to use onInit and onDestroy to keep the value but am unable to do…
Kanav Malik
  • 143
  • 1
  • 1
  • 12
1
vote
1 answer

HttpClient post not completing inside resolve guard unless piped through `take(1)`

I have an Angular application with routing and a resolve guard. The resolve guard is asynchronous and returns an observable returned from HttpClient.post - problem is, the AJAX request completes but the observable doesn't, and therefore the resolver…
Aviad P.
  • 32,036
  • 14
  • 103
  • 124
1
vote
0 answers

Delaying display of page until [ngClass] has been evaluated

Background I have a header component having [ngClass] attached to top div. Question Is it possible to delay displaying of page until [ngClass] has been evaluated? We used to have ng-cloak in AngularJs. Do we have something similar in Angular? Why I…
shobhit vaish
  • 951
  • 8
  • 22
1
vote
0 answers

Angular Dynamic Routing from API

Using Angular 6 I need to be able to fetch a set of routes from the backend, put them into the router.config, and then be able to navigate to the routes fetched. I am able to add routes in this way that are defined in typescript files, and I am able…
Mason Matlock
  • 65
  • 2
  • 8
1
vote
2 answers

Error: Cannot match any routes. URL Segment: 'table/3'

I'm trying to understand what I did wrong about the route with params. I have been follow the official guide about it (see on references below) The problem is that I followed all docs' instructions: defining the routing file, create my custom…
Francis Rodrigues
  • 1,470
  • 4
  • 25
  • 61
1
vote
0 answers

Angular remove # from URL

I'm using {provide: APP_BASE_HREF, useValue: '/'}, in my app.module.ts to remove hash from the URL localhost:4200/#/search. It worked fine in my local. The URL has changed to localhost:4200/search. It worked fine when I reload the page. I used ng…
Krishna
  • 1,089
  • 5
  • 24
  • 38
1
vote
1 answer

Uncaught (in promise): TypeError: Cannot read property 'component' of null, when trying to navigate to the same route with different parameters

I'm currently working on an Angular (v5.2.5) project, and I'm having some issues with the routing. Here are my routes: const routes: Routes =[ { path:'', component: ClassComponent}, { path: 'login', component: LoginComponent}, { path:…
mathi
  • 13
  • 3
1
vote
1 answer

Angular 5 Reload and build errors

Just a few issues here. One, when I use browser refresh it reloads back to / instead of the route that is loaded prior to the refresh. Below is my routes definition. const appRoutes: Routes = [ { path: '', component: LandingModule, canActivate:…
1
vote
1 answer

Shared Component with routerLink @Input()

I want to create a shared component, that has a button, and when clicked, routes the user somewhere. The route should come from the consumer of the component. How can I achieve this? I'm thinking I want to make the route an @Input() parameter. …
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
1
vote
2 answers

angular redirect to auth

I try use Angular Cli and Routing. I want made some routing /auth/login as default /auth/register ect I have 3 module app auth login on each level module i have definied route app.module const routes: Routes = [ { path: '', pathMatch:…
Dominik Kajzar
  • 124
  • 1
  • 11
1
vote
1 answer

Unable to navigate to route with ID in Angular

I am unable to navigate to route with ID argument when using router. Using this code inside my component import { Router } from '@angular/router'; ... constructor(private router: Router) { } ... public create() { ... …
Raphael
  • 990
  • 1
  • 13
  • 24
1
vote
1 answer

Multiple files to define routes

Normally I have a single file to define my routes, for example: app.routing.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import {…
Rafael Augusto
  • 777
  • 5
  • 14
  • 28
1
vote
1 answer

Angular 5, CanDeactivate hitting once with custom modal

Currently running angular 5 On one of our pages, we want a deactivate guard in place so that if a certain condition on the page is met (they start a test) and they attempt to navigate away without saving, they are presented with a custom modal (a…
dangerisgo
  • 1,261
  • 3
  • 16
  • 28
1
vote
0 answers

Angular routing keep child parameters

I have the following route configuration: const routes: Routes = [ { path: '', component: HomeComponent, canActivate: [AuthGuard], children: [ { component: DashboardComponent, path: '' }, { …
Rui Sebastião
  • 855
  • 1
  • 18
  • 36
1 2 3
99
100