Is it possible to extend an Angular component and then use the base component in an ngFor loop?

Can Angular components be extended? And if so, is it possible to create a list of diverse components (using an ngFor loop) that all extend a common base component?

For instance, could a custom menu bar display various types of menu items, such as dropdown menus, buttons, text boxes, etc., all extending the same "CustomMenuItem" component with shared functionality?

@Component({
    selector: 'custom-menu-bar',
    inputs: ['customMenuItems'],
    outputs: ['onMenuEvent'],
    template: `
        <div class="row">
            <custom-menu-item *ngFor="#item of customMenuItems">
                ...
            </custom-menu-item>
        </div>
    `
})
export class CustomMenuBar {
    customMenuItems: CustomMenuItem[];
    onMenuEvent: EventEmitter<MenuEvent>;

    //...
}

Answer №1

Angular 2.3 introduced Component Inheritance. Take a look at this sample code snippet (excerpted from an informative blog post):

@Component({
  selector: 'person',
  template: `<h4>Person: {{name}}</h4>`
})
export class Person {
  @Input() name: string;
}

@Component({
  selector: 'employee',
  template: `<h4>Employee: {{name}}, id: {{id}}</h4>`
})
export class Employee extends Person {
  @Input() id: string;
}

<div>
  <person name="John"></person>
  <employee name="Tom" id="45231"></employee>

Answer №2

If you're using Angular 2, DynamicComponentLoader can help you achieve this functionality. Check out the official documentation for more information.

Here is a code snippet from the documentation showcasing how to use DynamicComponentLoader:

@Component({
  selector: 'child-component',
  template: 'Child'
})
class ChildComponent {
}
@Component({
  selector: 'my-app',
  template: 'Parent (<div #child></div>)'
})
class MyApp {
  constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
    dcl.loadIntoLocation(ChildComponent, elementRef, 'child');
  }
}
bootstrap(MyApp);

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

I'm running into issues transferring data between Angular and an API

While working on an Angular project, I encountered an issue where I couldn't populate data from an API into a table. I suspected there was an error in the datasource section but couldn't pinpoint it. When checking the console, I verified that the ...

Module import in Ionic

I'm encountering an issue with Ionic, Angular, and TypeScript, and I'm feeling a bit lost... I'm trying to call an external function from my file but I keep getting the following error: "Uncaught (in promise): TypeError: undefined is not an ...

Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me: export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue; How should this type be unde ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...

Experience the latest happenings in SAP Spartacus 4.0 by signing up for updates directly from

I am facing an issue while trying to register an event in Spartacus import { Injectable } from '@angular/core'; import { CartDetailsComponent, PromotionService} from '@spartacus/storefront'; import { ActiveCartService, SelectiveCartServ ...

What is the best way to invoke a method from a class in Angular testing when the class has a Router constructor?

Currently, I am in the process of creating a test case for my authentication service outlined below. AuthService.ts import {Subject} from 'rxjs'; import {User} from './user.model'; import {AuthData} from './auth-data.model' ...

Managing a scenario with a union type where the value can be retrieved from one of two different functions

There are two similar methods that I want to refactor to eliminate redundant code. The first function returns a single element, while the second function returns multiple elements: //returns a single element const getByDataTest = ( container: HTMLElement ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

AngularJS using the ng-controller directive

I am presenting the following HTML code excerpt... <!DOCTYPE html> <html lang="en-US" ng-app> <head> <title>priklad00007</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angula ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

Managing numerous subscriptions to private subjects that are revealed by utilizing the asObservable() method

I'm using a familiar approach where an Angular service has a private Subject that provides a public Observable like this: private exampleSubject = new Subject<number>(); example$ = this.exampleSubject.asObservable(); In my particular situation, ...

Unable to access a function from a different controller within an AngularJS Ionic framework application

How can I trigger or call the callkhs function in the LihatKhsController from the KhsController? function KhsController($scope, $rootScope){ $scope.$emit('callkhs', {param:'test'}); } I am attempting to retrieve parameter values ...

Modifying Characteristics of Elements Added Dynamically

How do I change the type attribute for dynamically added buttons? In the code below, the label names are changing perfectly, but when I try to change button types, it applies to all dynamically added buttons. My requirement is to change every button type t ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Utilizing cross-platform configurations and functions across frontend and backend systems, such as integrating AngularJS with Django

Imagine a scenario where Django is used to create RESTful APIs for an AngularJS application. Both applications require configuration variables, some of which are shared. For instance, both applications need to access the list of holidays for the current ye ...

Leveraging CDK Context Variables in C# Lambda Initialization Code

I have a .NET Lambda function written in C# that is implemented as a .NET Minimal API according to the guidance provided here. To define AWS resources, I am utilizing CDK (TypeScript). Within my build pipeline, there is shell scripting involved to supply ...

Encountering a glitch with ng2-pdf-viewer on Angular version 13.2.2 and Ionic version 6

Issue reported: The following error message is encountered when trying to set up the PDF viewer: Error: Setting up fake worker failed: "Cannot load script at: https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.min.js". It is observed while ...

The function is producing inaccurate results when it is requested from a Flask app route

I am experiencing an issue with my app route as shown below: import myfile as myfilefunc @app.route("/data", methods=['GET']) def data(): file=request.args.get('file') p=myfilefunc.run(file) return json.dumps(p) ...

Using AngularJS `$state.go` to navigate without redirection in ExpressJS

I'm facing a strange issue with my ExpressJS setup for serving AngularApp Files locally. I have a main controller with the following code snippet: else{ console.log('Forwarding to Login'); $state.go('signin&apos ...