For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b
I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action.
For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b
I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action.
There is a clever and effective solution available if you prefer to handle this situation properly.
While many responses on this platform suggest using the back()
method in the Location
service, it's important to note that there is an issue with this approach. If a user opens a new tab, there may not be a history entry to navigate back to. This can potentially disrupt the Angular application and create security vulnerabilities since there is no direct API for examining browser history.
This solution is inspired by a helpful blog post authored by Nils Mehlhorn
Navigation Service
import { Injectable } from '@angular/core'
import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'
@Injectable({ providedIn: 'root' })
export class NavigationService {
private history: string[] = []
constructor(
private router: Router,
private location: Location
) {
// Listen to router events of type NavigationEnd to
// maintain an app-specific navigation history.
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.history.push(event.urlAfterRedirects);
}
})
}
/**
* Control the back navigation.
*/
back(): void {
this.history.pop();
// If there are still entries in the history after removing
// the current URL from the stack, it's safe to navigate back.
// Otherwise, default to returning to the application root.
if (this.history.length > 0) {
console.log('navigating back')
this.location.back();
} else {
console.log('navigating to /')
this.router.navigateByUrl('/');
}
}
}
Back button directive
import { Directive, HostListener } from '@angular/core';
import { NavigationService } from './navigation.service';
@Directive({
selector: '[navigateBack]',
})
export class BackButtonDirective {
constructor(private navigation: NavigationService) {}
@HostListener('click')
onClick(): void {
this.navigation.back();
}
}
Utilize the directive in HTML
<button navigateBack>
<mat-icon>arrow_back</mat-icon>Back
</button>
By utilizing angular's Router
and ActivatedRoute
, you can effectively navigate back from the currently activated route
constructor(private route: ActivatedRoute,private router: Router) {
}
this.router.navigate(['..'], { relativeTo: activatedRoute });
Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...
I'm facing an issue where the next and prev buttons are not visible on my carousel component, even though they seem to be working properly. When I inspect the elements, I can see that the buttons are there. How can I make them visible? Here is my cod ...
I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...
How can I properly emit an event in Angular (v.5 or v.6) after a specific input of a reactive form has been changed? Here are the approaches I have tried: (ngModelChange)="doSomething($event)" (HTML, basic event) (bsValueChange)="doSomething($event) ...
After thoroughly studying the Angular Material stepper documentation, I encountered an issue when attempting to integrate the HTML Material stepper tag into my Angular application. The error message stated that it's not a known element. HTML: <ma ...
I need help with implementing a feature where the user can select a starting price and an ending price, and based on that selection, I want to display relevant products without the need for a button. I want to achieve this using mat-slider to sort the prod ...
Is there a way to access an element that is defined in a component template? While Polymer has the $ and $$ to make this task simple, I am curious about how it can be done in Angular. Consider the example provided in the tutorial: import {Component} from ...
Is there a way to achieve the following setup: @RouteConfig([ { path: '/example/:name', name: 'Example', loader: (params: RouteParams) => { let name = params.get('name'); return _EXAM ...
As an example, if we consider a sample JSON data retrieved from the JSONPlaceholder website at https://jsonplaceholder.typicode.com/users. [ { "id": 1, "name": "Leanne Graham", "username": "Bret&q ...
I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...
I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...
In my code, I am creating a NavBar with items that may require fetching extra information from an API and adding it to the subtitle field. I want to transform this into an Observable<NavItem[]> so that it can be rendered using an Async Pipe. Curren ...
I need help converting the date property of an object to a format that the server can understand when using httpClient.post(...). Currently, the date property has its natural string representation. What steps can I take to make sure it is in the correct ...
I have integrated the ng2-adsense Google Adsense library into my Angular applications to display ads. To set it up, I followed the guidelines provided at this link: https://github.com/scttcper/ng2-adsense/ Include the adsbygoogle.js script in the head s ...
I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...
After reviewing several discussions regarding redirecting users to the previous page upon login or other actions, it appears that using HTTP_REFERRER to get the previous page URL is considered unreliable and insecure. My query is whether adding extra info ...
Hello, I am currently in the process of developing an Ionic2 framework app that includes social login functionality. Up to this point, I have successfully integrated Google Plus and Facebook buttons. Now, I would like to add LinkedIn login as well. The c ...
I am working with an array of objects. resources=[{name:'x', title:'xx',..},{name:'y',title:'yy',..}..] To populate my HTML tooltip, I am pushing all the titles from the resources array to a new array. dialogOkCli ...
I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...
I am working on a project using Ionic 2 and I have implemented multiple tabs in the application. However, I need to find a way to hide the top tab when the user clicks on the bottom tabs menu icon. Here is my Plunker for your reference. My goal is to ma ...