Use generics in Angular route

Issue

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’?"

Solution

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.

Answered By – BigJ

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.