1

I'm trying to clear input text by pressing buttons which send routing event. So, if I'm getting specific route and no parameters (see green buttons on screen below), then text box should be cleared. If route is incorrect, or correct but with the parameter (white buttons), then nothing should happen. I subscribe text box value name$ to ActivatedRoute event (I'm using routing service to pass data between unrelated components).

Logic, which I'm trying to implement:

  1. if route is '/welcome' or '/products' - continue.
  2. if there are params - ignore, return nothing, don't change input text.
  3. if no params, return empty string (clear input with "").

Concise demo application: github.com/sam-klok/AngularPlayRoutes

screen shot

HTML for main 1st component (menu):

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

HTML for 2nd/3rd component:

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

Code from 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 from 2nd/3rd component:

 export class WelcomeComponent implements OnInit {
 constructor(private activateRoute: ActivatedRoute, private router: Router){}
  btnClear(){
    // we already on welcome page this should clear text input
    this.router.navigate(['/welcome']);  
  }
sam sergiy klok
  • 526
  • 7
  • 17
  • Can you provide an example project (e.g. stackblitz) with your current implementation? What I can tell you already is that your `map` function is not correct. `EMPTY` returns an Observable but `map` should return a value. You could use `switchMap(searchTerm => searchTerm ? EMPTY : of(''))`. – Patrick Feb 28 '23 at 16:38
  • I will try to provide consise example in a few hours.. – sam sergiy klok Feb 28 '23 at 17:14
  • @patrick-s I added example on GitHub, not sure how to get this proj on StackBlitz.. https://github.com/sam-klok/AngularPlayRoutes – sam sergiy klok Mar 01 '23 at 06:15
  • Does `map(x => { return x ? x : '' }),` work for you? And if not what change of behaviour is intended? – Patrick Mar 01 '23 at 07:11
  • It does not, it's always return 'undefined'. It's leftover from yesterday test app preparation.. – sam sergiy klok Mar 01 '23 at 14:16

1 Answers1

0

Per my testing, ActivatedRoute always have property ULR empty. Strange, why? Not sure..

Alternative solution without ActivatedRoute, but with Router answered here: 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))
);
sam sergiy klok
  • 526
  • 7
  • 17