Tips for utilizing the @Component decorator in both abstract classes and their implementations within Angular 8

While working with Angular 8, I am attempting to utilize abstract components. My goal is to define the templateUrl and styleUrls in my abstract class, but have the selector name specified in the implemented class. Here is an example:

@Component({
  // selector isn't defined here
  templateUrl: './abstract-list.component.html',
  styleUrls: ['./abstract-list.component.scss']
})
export abstract class AbstractListComponent<T> implements OnInit {
  // ...
}

In the child class:

@Component({
  selector: 'app-my-custom-list',
  // templateUrl & styleUrls should be inherited
})
export class MyCustomListComponent extends AbstractListComponent<MyCustomListInterface> implements OnInit {
  // ...
}

I attempted to use the decorator only in the implementation like this, but I believe there must be a better way:

@Component({
  selector: 'app-my-custom-list',
  templateUrl: '../../abstract-list/abstract-list.component.html',
  styleUrls: ['../../abstract-list/abstract-list.component.scss']
})

Is it feasible to use the @Component decorator in a manner similar to this? Alternatively, is there a trick or best practice for achieving this type of usage?

Answer №1

Thanks to the valuable input from @Rectangular, I approached the problem in the following manner:

In the abstract class:

export const componentDecoratorPreset = {
  // selector is not defined here
  templateUrl: './abstract-list.component.html',
  styleUrls: ['./abstract-list.component.scss']
};

export abstract class AbstractListComponent<T> implements OnInit {
  // ...
}

Subsequently, in the implementation:

import { AbstractListComponent, componentDecoratorPreset } from 'src/app/components/_absrtact/list/abstract-list.component';

@Component({
  ...componentDecoratorPreset,
  selector: 'app-my-custom-list',
})

Naturally, this approach did not work as expected due to the relative path specified in the templateUrl which did not correspond to an existing file in the implementation.

Therefore, I attempted to use absolute paths in the abstract class as demonstrated below:

export const componentDecoratorPreset = {
  // selector is not defined here
  templateUrl: 'src/app/components/_absrtact/list/abstract-list.component.html',
  styleUrls: ['src/app/components/_absrtact/list/abstract-list.component.scss']
};

Despite the Angular documentation suggesting the possibility of using relative or absolute paths for templates, I encountered issues with absolute paths. Upon further investigation, I came across an article explaining why absolute paths are not suitable. Nevertheless, I devised a solution inspired by the article:

I created a abstract-list.component.html.ts file with the following content:

export default `<div class="container-fluid">...abstract template content...</div>`

Subsequently, I imported this template as a variable in the abstract class and exported it as an object:

import template from './abstract-list.component.html';

export const componentDecoratorPreset = {
  // selector: to be defined in the implementation
  template: template as string,
};

Finally, in the implementation:

import { Component, OnInit } from '@angular/core';
import { AbstractListComponent, componentDecoratorPreset } from 'src/app/components/_absrtact/list/abstract-list.component';
import { AddressTypeInterface } from 'src/app/models/address/type/address-type.interface';
import { AddressType } from 'src/app/models/address/type/address-type.model';

@Component({
  selector: 'app-address-type-list',
  ...componentDecoratorPreset
})
export class AddressTypeListComponent extends AbstractListComponent<AddressTypeInterface> implements OnInit {
  constructor() {
    super(AddressType);
  }
}

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 best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Navigating through PWAs and implementing deep linking in both single page applications (SPAs) and multi-page applications

QUESTION: How can navigation, history, and deep-linking be managed in a PWA without relying on a heavy JS Framework? Tasked with transitioning an existing shopping website from Angular 1 SPA to a Multi Page App (MPA) PWA, I find myself grappling with desi ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

[deactivated]: Modify a property's value using a different component

One of the requirements for my button is that it should be disabled whenever the callToActionBtn property is true. match-component.html <button [disabled]="callToActionBtn" (click)="sendTask()>Send</button> match-component.ts public callToA ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

The error TS2304 in @angular/common is indicating that the name 'unknown' cannot be found

I am struggling to revive an old project due to some errors. I am using Angular 5.2.9 for the build, but these errors keep popping up. If anyone can offer assistance, I would greatly appreciate it. This is how my package.json file appears: "dependencies" ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

The creation of a fresh child instance in Typescript using rest parameters

My goal is to create a parent class that allows children to generate new instances of the same child type. When I specify the number of parameters, everything functions correctly: abstract class AClass { protected sameTypeWithSingle ( x: any ): t ...

Struggling with a TypeORM issue while attempting to generate a migration via the Command Line

Having some trouble using the TypeORM CLI to generate a migration. I followed the instructions, but when I run yarn run typeorm migration:generate, an error pops up: $ typeorm-ts-node-commonjs migration:generate /usr/bin/env: ‘node --require ts-node/regi ...

Obtain the parameters of a function within another function that includes a dynamic generic

I am attempting to extract a specific parameter from the second parameter of a function, which is an object. From this object, I want to access the "onSuccess" function (which is optional but needed when requested), and then retrieve the first dynamic para ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

LightWeightChart: How do I incorporate a chart that resembles this style?

Is it possible to create a chart using lightweight-chart that includes two graphs sharing the same x-axis but with different values on the y-axis? Essentially, I want to have two panes in a single chart. Does anyone have suggestions or tips on how this c ...

Creating an application using AngularJS 4 and the Express generator

Recently, I successfully created a basic angular 4 application using this helpful tutorial: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli My next challenge is integrating the angular 4 app with an express application generated b ...

angular 2 updating material table

Issue at Hand: I am facing a problem with the interaction between a dropdown menu and a table on my website. Imagine the dropdown menu contains a list of cities, and below it is a table displaying information about those cities. I want to ensure that whe ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

The system encountered an issue while trying to access the property 'emailVerified' of an undefined object

I am currently working on retrieving the current user and attempting to assign the user values to a getter. In the constructor, I can see in the console that it is returning "email verified" as true. However, when trying to set it in the getter, I am enc ...

Unsure about module loading with system.js and navigating Typescript

I am currently in the process of transitioning an ASP.Net MVC application to Angular2, and I've encountered some perplexing behavior that I can't seem to grasp. Within my Angular2 app, I have a separate Layoutview that allows me to switch betwee ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...