1

I want to know if it's possible to use (Typescript) generics in a Angular Route, in any way possible.

Best way would be if I could use generics with the component itself:

// the route:
{
  path: 'user-a',
  component: UserComponent<UserA> // other routes will use UserB and UserC
}

// the component:
@Component({...})
export class UserComponent<T> { ... }

This obviously gives an error, but it gives a good idea of what I want to accomplish.

Another method would be to use generics with the Resolver:

// the route:
{
    path: '/user-b',
    component: UserComponent, 
    resolve: { user: UserResolver<UserB> }
}

// the resolver:
export class UserResolver<T> implements Resolve<boolean> {}

This answer used this method, but for me it gives an error at UserResolver<UserB>: "Value of type 'typeof UserResolver' is not callable. Did you mean to include 'new'?"

BigJ
  • 1,990
  • 2
  • 29
  • 47
  • 1
    Just curious.. but why would you want this..? What does this give you on the component side? – MikeOne Dec 23 '20 at 21:13
  • 1
    @MikeOne Good question. Actually I'm sending the components to a private library to make dynamic components. For simplicity I just explained the problem in general. – BigJ Dec 23 '20 at 21:41

1 Answers1

1

Not sure how I could of missed this, but the value of a data property on a angular Route can be of any type. Which means you can do this:

// the route in app-routing.module.ts
{
  path: 'user-a',
  component: UserComponent,
  data: {
    componentType: UserA
  }
}

// UserComponent:
@Component({...})
export class UserComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    const componentType: any = this.route.snapshot.data['componentType'];
  }

}

Somehow I always assumed the value of a data property could only be a string, but the docs clear state any.

BigJ
  • 1,990
  • 2
  • 29
  • 47