What is the process for subscribing to the ActivatedRoute change event and extracting the URL along with its parameters?

My goal is to clear the input text by pressing buttons that send routing events. If a specific route is received without any parameters (indicated by green buttons on the screen below), then the text box should be cleared. If the route is incorrect, or correct but with parameters (white buttons), then nothing should happen. I am subscribing to the text box value name$ in the ActivatedRoute event (I am using the routing service to pass data between unrelated components).

The logic I am trying to implement is as follows:

  1. If the route is '/welcome' or '/products' - continue.
  2. If there are params, ignore them, do not change the input text.
  3. If there are no params, return an empty string (clear the input with "").

For a concise demo application, visit: github.com/sam-klok/AngularPlayRoutes

https://i.sstatic.net/0VZaM.png

HTML for the main 1st component (menu):

<input #name type="text" [value]="(name$ | async)" placeholder="name"/>

HTML for the 2nd/3rd component:

<button (click)="btnClear()">Clear input above</button>

Code from the 1st component (which is currently not working) app.component.ts:

export class AppComponent {
  name$ = this.activateRoute.queryParams.pipe(
    map(params => params['name']),
    map(x => {return x}))

Code for the 2nd/3rd component:

 export class WelcomeComponent implements OnInit {
 constructor(private activateRoute: ActivatedRoute, private router: Router){}
  btnClear(){
    // we are already on the welcome page, this should clear the text input
    this.router.navigate(['/welcome']);  
  }

Answer №1

According to my experiments, it seems that the ActivatedRoute always has an empty URL property. This behavior is quite strange and perplexing.

If you are facing issues with ActivatedRoute, you can consider an alternative solution using the Router. I found a helpful answer on Stack Overflow that discusses how to reactively subscribe to URL changes and retrieve the URL in an Angular RxJS context: How to reactively subscribe to URL change and get URL in Angular RxJS?

import { Router, NavigationEnd } from '@angular/router';
import { map, filter } from 'rxjs/operators';
url$: Observable<string> = new Observable<string>();
this.url$ = this.router.events.pipe(
  filter((event: any) => event instanceof NavigationEnd),
  map((event: NavigationEnd) => JSON.stringify(event.url))
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

How to link data from a service to an Angular component in a way that ensures the component gets updated whenever there is new data in the service

When data is updated in a service, how can I ensure that the changes are reflected in a component? In my application's header, there is a button that allows users to switch between English and Spanish. However, while the text in the header (a compone ...

Unable to find the specified webpack in the source map

In my Visual Studio Code project, I have designed a website using Angular as part of a class assignment. However, there seems to be an issue with one of the pages as it fails to load when I try to navigate to it. Instead, my browser shows a pop-up message ...

"Encountering a Cypress Angular error: CypressError with the message 'Timed out retrying: Expected content was not

During my Cypress test run, I encountered an error message on the last step (click) which stated: Timed out retrying: Expected to find element: .button-darkblue, but never found it. Here is the code snippet: describe('Test Login', () => { i ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Guide on setting the focus of an input in a form field using ngIf

I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true inside the ngOnInit() method. export class InputOverviewExamp ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

ag-grid provides unique filter options for custom date filtering in Angular 2

Currently, I am attempting to assign new options to a date column field by using the following method. However, these new options are not being displayed in the grid. let dateValues = ["equals", "inRange","quarter1","quarter2","quarter3","quarter4"]; { ...

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...

Use Typescript to access and utilize the value stored in local storage by using the

Trying to retrieve the language setting from localHost and implement it in a translation pipe as shown below: transform(value: string): string {... localStorage.setItem("language", JSON.stringify("en")); let language = JSON.parse(loca ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Utilizing Bootstrap 5 for Angular Projects

With the release of version 5, the Bootstrap framework has eliminated the need for jQuery. I am curious about how this change impacts Angular applications. Can we still utilize all of Bootstrap's features in Angular, such as dropdowns? In the past, ...

Turn off ESLint for TypeScript documents

I am faced with a large web application that consists of legacy JavaScript code (with eslint) and new TypeScript code (with tslint). The issue I am encountering is that my IDE (WebStorm) is running both linters on all files, causing me to receive eslint e ...

Numerous documents for route definitions

Typically, I usually have all my route definitions in a single file, such as app.routing.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@a ...

How can I adjust the width of a td table in an Angular 6 component template using Bootstrap?

I am currently working on a project using Angular 6. Here is a snapshot of the screen I am working on: https://i.stack.imgur.com/hQLOI.png The screen consists of two main elements - an HTML table and a component that represents the table data in individ ...

Creating a specialized feature for saving form data with React Admin

Within my react-admin application, I am faced with a scenario where I have a list of items accompanied by two separate buttons: "Create using email" and simply "Create". The "create" button utilizes the functionality provided by the data provider, which is ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Challenges with E-commerce Project's Wishlist Feature

Currently, I am working on a project where clicking on the 'fa-heart' icon should toggle between solid and regular states to add or remove an item from the wishlist. However, my attempts so far have resulted in all product icons changing together ...

Leveraging Angular 2 to retrieve information from mongoDB

I recently finished setting up my nodejs project which includes a database and some data. The database was created using the following URL: mongodb://localhost:27017/ Check out the code snippet below: var MongoClient = require('mongodb').MongoC ...