Building upon the foundation: Extending a base component in Angular

I have a Base Component that is extended by its children in Angular. However, when creating a new Component using angular-cli, it generates html and css files that I do not need for the base component.

Is there a way to create a Base Component without including html and css files?

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-base',
  templateUrl: './base.component.html', //I dont need this
  styleUrls: ['./base.component.css'] ////I dont need this
})
export class BaseComponent implements OnInit {

  constructor() {}

  ngOnInit() {}

}


import { Component } from '@angular/core';

import { BaseComponent } from '../base/base.component';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent extends BaseComponent {

  constructor() {
    super();
  }

  ngOnInit() {
  }

}

Answer №1

If the base class does not need to be instantiated on its own, it is considered an abstract class and does not require the @Component decorator.

However, if the base class has dependencies and there is a possibility that the constructor may be omitted in child classes and inherited, then the base class should have the @Injectable decorator:

@Injectable()
export abstract class BaseComponent implements OnInit {
  constructor(public dep: Dep) {}

  ngOnInit() {}
}

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent extends BaseComponent {
  // The dummy constructor can be omitted
/*
  constructor(dep: Dep) {
    super(dep);
  }
*/
}

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

Sorting items in Ag-Grid according to user's preference

Here is an example of a header in ag-grid with custom sorting applied: { headerName: "StudentId", field: "StudentId", width: 140, editable: false, enableRowGroup: true, comparator: (valA, valB, n1, n2, inver ...

Issue with TypeScript Decorator Not Properly Overriding Get/Set Functions for Instance Properties

I'm struggling with creating a TypeScript decorator that modifies the get method for a property within a class. The issue I'm facing is getting it to affect instances of the class. Below is an example scenario: function CustomDecorator() { r ...

Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have: enum A { dog = 1, cat = 2, ant = 3 } Desired output: ["dog", "cat", "ant"] achieved by: Object.values(A) Unfor ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

React Typescript can easily differentiate between various prop types by selecting either of the two types

I am working with two Typescript interfaces: type ISecond = { timeType: string secondTime: number } type IDay = { timeType: string startTime: number endTime: number } When it comes to my react function props types, ... const CountDown ...

The property 'matCellDefTrackBy' cannot be bound to 'mat-cell' as it is not recognized as a valid property

Wondering how to implement trackBy in Angular Material? I encountered the error message below: Can't bind to 'matCellDefTrackBy' since it isn't a known property of 'mat-cell' html: <mat-table [dataSource]="data" ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Add a hash to the file name of the JSON translation asset

To prevent caching issues, I choose to store my translation files as JSON in /src/assets/i18n. To achieve this in Angular, I am looking for a way to add a unique fingerprint or hash to the filename of the file and use that hashed name when retrieving the ...

Can you use getters and setters in a TypeScript declaration file?

I am facing an issue with a declaration file for the openUi framework. The framework utilizes a get<propname>() and set<propname>(var) syntax for its properties. In traditional JavaScript, the setup would look like this: sap.ui.getCore().atta ...

Difficulties arise when attempting to install nodejs on linux using the npm install nodejs command

While attempting to execute... npm install nodejs I encounter the subsequent issue: npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email prot ...

Can you modify a specific column in a table using mat-table in Angular material?

For my project, I am utilizing Angular Material's table to present data in a tabular format. However, due to a new requirement, I now need to enable in-line editing for the last 2 columns alongside highlighting another column when the user clicks on t ...

Improve the way you manage the active selection of a button

ts isDayClicked: { [key: number]: boolean } = {}; constructor() { } setSelectedDay(day: string, index: number): void { switch (index) { case 0: this.isDayClicked[0] = true; this.isDayClicked[1] = false; this.isDay ...

PhpStorm is unable to resolve the @ionic/angular module

I have encountered a peculiar issue with my Ionic v4 project. While the project runs smoothly, PhpStorm seems unable to locate my references to @ionic. https://i.stack.imgur.com/umFnj.png Interestingly, upon inspecting the code, I realized that it is act ...

The parent class has not been specified

I am facing an issue with my parent class, HTTPConnection, which I intend to use as a network utility class in order to avoid redundant code. However, when attempting to utilize it, the file core.umd.js throws an error stating Uncaught ReferenceError: HTTP ...

How to apply conditional styling to text using Angular2

I need to display a list of objects that contain names and numbers. The color of the name should change based on the number associated with it - red for 1, blue for 2, green for 3, and orange for 4. My template currently looks like this: <p *ngFor="l ...

Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have: <form [formGroup]="myForm" (ngSubmit)="onSubmitted()"> <app-names></app-names> <app-address> ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Using MatTableDataSource in a different Angular component

I am working with two components, namely Order and OrderDetail. Within the Order component, I have a MatTableDataSource that gets populated from a service. OrderComponent Prior to the constructor listData: MatTableDataSource<DocumentDetailModel>; ...