import RouterModule in module.ts file import { RouterModule } from '@angular/router'; import router module component.ts file import { Router } from '@angular/router'; constructor(private router:Router){}
in Angular 16+ for standalone import { RouterModule, Router } from '@angular/router'; import { inject } from '@angular/core'; @Component({ selector: 'my-router', standalone: true, imports: [ ..., RouterModule, ... ], templateUrl: './my.component.html', styleUrl: './my.component.scss' }) private router = inject(Router);
below code can used for angular 2+ and standalone
yourFun(){ this.router.navigate(['/myRoute']); //to pass the parameter as slug this.router.navigate(['/myRoute', 'myId']); //output will be like this www.https://localhost:4200/myRoute/myId //to pass the parameter as query params this.router.navigate([ url ], { queryParams: { myId:42 } }) //output will be like this www.https://localhost:4200/myRoute?myId=42 } //for html in your ts file make it as public constructor(public router:Router){} or public router = inject(Router); //normal redirection Somewhere //redirection with queryParams Somewhere //redirection with slug Somewhere
The $location service in AngularJS is used to get or set the URL in the browser. To redirect using $location, you can inject the $location service into your controller or component and use the path() method to change the URL.
angular.module('myApp', []) .controller('MyController', ['$location', function($location) { $location.path('/newPage'); }]);
If you want a full page reload during the redirection, you can use the $window service to manipulate the browser’s location.
angular.module('myApp', []) .controller('MyController', ['$window', function($window) { $window.location.href = '/newPage'; }]);
First, configure your routes in the config block:
angular.module('myApp', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/home', { templateUrl: 'home.html', controller: 'HomeController' }) .when('/newPage', { templateUrl: 'newPage.html', controller: 'NewPageController' }) .otherwise({ redirectTo: '/home' }); }]);
Then, use $location.path('/newPage') to navigate to the new page: angular.module('myApp') .controller('HomeController', ['$scope', '$location', function($scope, $location) { $scope.redirectToNewPage = function() { $location.path('/newPage'); }; }]); In your HTML, you can call the redirectToNewPage function: