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

2
  • 1
    Just curious.. but why would you want this..? What does this give you on the component side? Commented Dec 23, 2020 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. Commented Dec 23, 2020 at 21:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.