Mario M.
Mario M.

Reputation: 416

How to reuse a component code (Angular2 + TS)

Creating a small Angular 2 app (A calculator for a nice game called AbyssRium), I'm trying to reuse the code of a simple component that shows a list of elements. I want those components to show only a subset of elements (filtered by group).

I'm not sure if it's possible to do it using the RouteConfig (passing a parameter), but it would be a good option. I tried to understand 'Routes' the documentation (here and here ) but I couldn't see any clear reference (now playing with Resolve, but no results yet). I'm looking for something like this:

@RouteConfig([
  {path: '/corals', name: 'Corals', component: ItemsList, data:{group:'coral'}, useAsDefault: true},
  {path: '/fishes', name: 'Fishes', component: ItemsList, data:{group:'fish'}},
])

I also tried to inherit the module (ItemsList -> ItemsCoralList & ItemsFishList), and initialize the class (this.group = "coral") in the constructor, but tons of compilation errors appear:

Cannot resolve 'xxx'. Make sure they all have valid type or annotations.

Any idea how to do it without copying all the code twice?

Here the code at Plunker

Upvotes: 0

Views: 366

Answers (1)

Sasxa
Sasxa

Reputation: 41264

You can use:

{path: '/:group', component: ItemsList}

And access it via router

constructor(route: ActivatedRoute) {
  this.route.params.subscribe(params => params.group)
}

Note: this is Router 3.x syntax, it's probably not gonna work out of the box - you should upgrade to final...

Upvotes: 2

Related Questions