0

Atm I am using Angular router. At the parent route, I have a component render with default state (tabIndex = 0).

Desired Behaviour: At a child route, I would like to be able to change the tabIndex state on the same component.

Options considered

1. Using data

I have successfully been able to differentiate paths by adding data and subscribing to the activatedRoute's children's data.

this.route.children.forEach(c => c.data.subscribe(cd => console.log(cd, 'child data'))

Angular router - empty data object for child routes

2. Using parameterization

Someone also suggested that I could use a parameterized subroute and do a regex match.

Routing module segment that defines relationship:

{
        path: 'parent-path/:id',
        component: MyComponent,
        children: [{
          path: ':child-path'
          component: MyComponent,
        }]
},

--

What's the best way to accomplish this?

Neither option feels particularly great, especially since I will have multiple levels of parent/child relationships. Does anyone have any advice or thoughts. I haven't been able to find any other meaningful options for this and I am new to ng, so any advice or thoughts would be appreciated!

K.F
  • 459
  • 3
  • 12
  • What is meant by "tabIndex state" – JWP Aug 02 '19 at 15:25
  • There's a tabindex state on the component that determines which is currently active. But there are other use cases, I meant only to provide an example of one. – K.F Aug 02 '19 at 15:55

1 Answers1

0

Personally, I like using services to communicate between children and parent(s).

//sharedService.ts

 private _tabIndex$ = new Subject<number>();
 public tabIndex$ = this._tabIndex$.asObservable();

 ngOnDestroy():void {
     this._tabIndex$.complete();
 }

 setTabIndex(index: number): void {
     // validate it is a number

     this._tabIndex$.next(index);
 }

// parentComponent.ts

private _destroy$ = new Subject<void>();
constructor(
   private _sharedService: SharedService
){
    this._sharedService.tabIndex$.pipe(
      takeUntil(this._destroy$)
    ).subscribe(index => // do something);
}

ngOnDestroy():void {
    this._destroy$.next();
    this._destroy$.complete();
}

// child

constructor(
 private _sharedService: SharedService,
 private _route: ActiveRoute
){
  const tabIndex = this._route.snapshot.data.tabIndex || null;
  if(tabIndex != null){
     this._sharedService.setTabIndex(tabIndex);
  }
}

The child component will send tabIndex itself.

This code could be put in a generic component class and extend every component that will be send its tabIndex, so you do not have add this code in every component.

mr.vea
  • 424
  • 2
  • 8