Tips for Recycling a Component Code (Angular2 + TypeScript)

Working on a small Angular 2 app for an AbyssRium game calculator, I am attempting to repurpose a basic component that displays a list of items. My goal is to have these components display only a specific subset of elements based on filtering by group.

I'm exploring the possibility of achieving this through RouteConfig (by passing a parameter), although I'm not entirely certain if it's feasible. I've been trying to grasp the concept of 'Routes' from the documentation (here and here) but so far, I haven't come across any clear references (currently experimenting with Resolve without much success). This is what I envision:

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

In addition, I attempted to create submodules (ItemsList -> ItemsCoralList & ItemsFishList) and set the class initialization (this.group = "coral") in the constructor, yet encountered numerous compilation errors:

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

Any suggestions on how to achieve this without duplicating the entire code?

You can find the code snippet on Plunker

Answer №1

If you want to utilize the following code snippet:

{path: '/:category', component: ProductsList}

You can access it using a router like this:

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

Please be aware that the syntax shown above is for Router 3.x, so it might not work straight away - consider upgrading to the final version.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for defining a property type as a textual representation of a Type name in TypeScript?

Consider the following classes and interface: class Foo {} interface Bar {} I am looking to define a type that includes a property with a specified type: type DynamicPropertyName<T> = ... <-- ??? After defining the type, I want to use it like th ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

The system failed to acknowledge 'nodemon' as a command, either internally or externally, as an executable program, or as a batch file

Having trouble installing nodemon globally? I'm encountering a warning message, which is possibly preventing nodemon from running properly. Here's a snippet from my package.json file: { "name": "learn", "version": "1.0.0", "descriptio ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

Implementing React Router with dynamic parameters in the root element

I'm in the process of transforming an ASP.NET MVC application to utilize React with Redux in TypeScript. I've opted for React Router for handling the routing, with a necessary parameter in the root URL to specify the customer's organization. ...

Deconstructing Angular 2 Custom Pipes

As I delve deeper into learning Angular 2, my recent endeavor involves creating a custom pipe to filter results in my gallery by category. Unfortunately, the resources I've been referring to lack detailed explanations on how custom pipes actually work ...

How can I incorporate shared Angular 2 components in my Angular 2 web application with the help of webpack?

I've been attempting to incorporate shared angular-2 components into another angular-2 web project by duplicating them in the node_modules folder. Unfortunately, this method has not proven successful. You can access the entire project at Ng2-Webpack- ...

Utilizing the Controller with react-hook-form and material-ui to enhance the functionality of the FormControlLabel and

When using Material-ui with react-hook-form, it is recommended to use <Controller along with the render method instead of using "as = {xy-control}". Additionally, avoid mixing controller with inputRef = {register}. Using a single control is not an issue ...

Exciting ngClass variation

I am facing a challenge of adding multiple classes to an element, with one of them being conditional. After referencing the documentation, I came across this method: <some-element [ngClass]="{'first': true, 'second': true, 'thi ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

Encountering a 400 error when attempting to make a

After recently starting to use angular5, I encountered an error when attempting to insert a new row of data into a table. The error message was Failed to load resource: the server responded with a status of 400 (Bad Request) I've experimented with bo ...

The Firebase EmailPasswordAuthProvider is not a valid type on the Auth object

When working in an Angular2/TypeScript environment, I encountered an error when trying to use the code provided in the Firebase documentation. The error message displayed was "EmailPasswordAuthProvider Does Not Exist on Type Auth". var credential = fireba ...

Ignoring HTML's required validation in Angular 4?

Angular 4 appears to be disregarding the standard HTML validation. Is there a way to prompt Angular to recognize required fields for input elements? Intended behavior: https://i.sstatic.net/TsJcT.png sample code: <form #loginForm="ngForm" ...

Retrieving the value of an object using a key in TypeScript

Is there a way to create an object using keys from another object and determine the type based on a string? For example: const result = rebuild(query, { name: 'string' }); // query - { name: '123', dont_need: true } // result - { n ...

Error: The DatePipe in Angular is throwing an InvalidPipeArgument when trying to convert the object "[object Object]" into a date using data from PHP

I have an app built using Angular 9 and an API built with PHP. The PHP controller returns a list of objects with a property called finishDate. In PHP, finishDate is assigned to a DateTime object: $timeSheetsOrderDTO1 = new TimeSheetsOrderDTO; $timeSheetsOr ...

Challenges encountered when setting a value to a custom directive via property binding

I'm working on a question.component.html template where I render different options for a specific question. The goal is to change the background color of an option to yellow if the user selects the correct answer, and to red if they choose incorrectly ...

Effortlessly bring in Typescript namespace from specific namespace/type NPM package within a mono-repository

Instead of repeatedly copying Typescript types from one project to another, I have created a private NPM package with all the shared types under a Typescript namespace. Each project installs this NPM package if it uses the shared types. index.d.ts export ...

What is the reason for the lack of functionality of the "unique" field when creating a schema?

I've created a schema where the username field should be unique, but I'm having trouble getting it to work (The "required" constraint is functioning correctly). I've tried restarting MongoDB and dropping the database. Any idea what I might b ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...