What is the recommended input variable type for an Angular component?

I am currently working on developing a reusable module. Within this module, I aim to create a functionality that allows for opening different components using the MatDialog. Let's refer to one of these components as StartActionComponent. Typically, I would utilize the following code:

export class StartActionComponent{

  async startbuttonClicked(e: SomeEvent){
    const dialogRef = this.dialog.open( SomeModalComponent , {data: e});
  }
}

This approach works effectively; however, I now seek to dynamically inject another component, for instance, SomeModalComponent2. My attempts to achieve this are outlined below:

DashboardModule

export const START_COMPONENT = new InjectionToken<any>('START_COM');

export class DashboardModule {

  static forRoot(conf: {
    onStart: any
  }):ModuleWithProviders<DashboardModule>{
    return {
      ngModule: DashboardModule,
      providers: [
        {
          provide: START_COMPONENT, useValue: conf.onStart
        }
      ]
    }
  }
}

within the StartActionComponent component.

StartActionComponent

constructor(
    @Inject(STOP_COMPONENT) startComponent: any) {}

  async startbuttonClicked(e: SomeEvent){
    const dialogRef = this.dialog.open( this.startComponent , {data: e});
  }

and within app.module.ts

AppModule

import { SomeModalComponent2 } from 'some.modal2.component`;

@NgModule({
  import: [DashboardModule.forRoot(onStart: SomeModalComponent2)]
})

My goal is to exclude the use of any and define a specific type for:

static forRoot(conf: {onStart: any})

or

@Inject(STOP_COMPONENT) startComponent: any) {}

Although I have attempted utilizing ComponentType, I have had little success.

Answer №1

Once, I faced a scenario where I needed to specify the types for my dynamic components. To address this, I created a new file named DynamicComponents.ts and included the following code snippet:


export type DynamicComponentType = Component1 | Component2 | Component3 | Component4;

For your situation, you might need something similar like:


export type CustomComponentType = Modal1 | Modal2;

I believe this solution aligns with your requirements,

Answer №2

Previously, my go-to method was using

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

According to the documentation:

@description
Represents a type that a Component or other object is an instance of
An example of a Type is MyCustomComponent class, which in JavaScript is represented by the MyCustomComponent constructor function.

export declare const Type: FunctionConstructor;

When it comes to the generic <T> parameter, for your case using any is recommended. This will require you to provide a component of any type, ensuring it remains a component - inputs like numbers/booleans/strings, etc. would be considered invalid

An alternative approach could be utilizing ComponentType from

import { ComponentType } from '@angular/cdk/portal/portal';
. However, this requires installing the cdk package and the interfaces appear identical (apart from the extension)

export interface ComponentType<T> {
    new (...args: any[]): T;
}

// vs.

export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}

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

Unlocking Angular 10: Harnessing the Power of JWT for Seamless

I am encountering an issue with JWT login in angular. Although I have successfully logged in and saved the token, my frontend isn't reflecting the changes Auth.service.ts import { Injectable } from '@angular/core'; import { HttpClient, Http ...

What is the best way to restore an Angular 4 FormGroup to its initial state?

I have been delving into Angular4, specifically reactive forms. While experimenting with the Heroes demo, I encountered a hurdle. On this Plunker example, we are required to select a superhero and view their corresponding addresses. I added a reset button ...

Oops! ExcelJs is throwing an error: "Unable to merge cells that are already

Currently, I'm attempting to create an Excel sheet using excelJs. Each order has an array of order items, which could be one or more. My goal is to avoid repeating certain information within the order while iterating through each item in the order. Ho ...

Tips for ensuring the HTML checkbox element is fully loaded before programmatically selecting it

When a user accesses the page, I want certain checkboxes to be automatically checked. To achieve this, I am storing the IDs of the HTML checkbox elements in a service. Upon entering the page, the service is utilized to retrieve an array containing these ID ...

Scroll to the bottom of the text area or input field - Ionic 3, Angular 2+

Whenever I attempt to use the method provided below, my cursor seems to not move to the end of the textarea as expected. Instead, it appears at the beginning, making editing impossible. How can I find a solution to this issue? HTML <button ion-button ...

Stop users from switching to other tabs within mat-tab-group without using ViewChild

I am working with a mat-tab-group component in Angular : mat-tab-group class="brand-tabs" [disableRipple]="true" *ngSwitchCase="types.project" (selectedTabChange)="changeProjectTab($event)" [selectedIndex]="selectedProjectIndex" > . ...

The element 'router-outlet' is unrecognized

I am working on an MVC 5 project with an Angular frontend. I decided to implement routing following a tutorial from https://angular.io/guide/router. In my _Layout.cshtml, I included the following: <base href="/"> Then, I set up my routing in my app ...

Is there a way to define an object's keys as static types while allowing the values to be dynamically determined?

I am attempting to construct an object where the keys are derived from a string union type and the values are functions. The challenge lies in wanting the function typings to be determined dynamically from each function's implementation instead of bei ...

Dynamic Angular routes with varying numbers of parameters

I am working on developing an application where I need to associate TreeList navigation with routes. Consider the file structure in the explore section: - desktop - file1.txt - pictures - wallpaper - my-selfie.png - file2.txt - file4. ...

Execute a single module within the main thread of an Angular web worker project

Imagine working on a project in Angular with a focus on performance. The goal is to run the app on webworkers, while still being able to manipulate the DOM using an external library such as Google Maps. How can we achieve this balance? To streamline the p ...

How to ensure complete unit test coverage for ngx bootstrap modal in Angular?

In my quest to write unit tests, I encountered the following code snippet that needs testing: onLogon(event: any, resetPassword = false): void { this.bsModalRef = this.modalService.show( LoginComponent, Object.assign( ...

Convert integers to decimal numbers using Angular framework

Hello, I've been trying to convert the price integer to a decimal number. For example: 900 should become 9,00 or 950 should become 9,50. I have tried various methods that I found on this platform, but it always displays as 900 or 900,00 instead of 9, ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Utilizing ActivatedRoute in conjunction with another Service

I am facing an issue while trying to utilize the ActivatedRoute service in a different service. The problem lies in the fact that when I use the ActivatedRoute service in my service, it is observing the main App component and not picking up any route param ...

Cypress terminal issue: Cannot find property in 'cy & CyEventEmitter' type

Tech stack: Angular v15 and Cypress V12 Despite successful runs of my component and end-to-end tests, I encounter peculiar terminal errors while running the tests. The issue could potentially stem from my Cypress configuration for shared commands. Here ...

The data in DataTables is loading correctly, however, the buttons and sorting features are not operating as intended within Angular 4

I am currently working on an Angular 4 project where I need to display data in a table format using the DataTables library. While I have successfully implemented the hardcoded examples provided by DataTables with all the buttons functioning as expected, I ...

Using Promise.all for multiple function calls

I have several functions set up like this: private async p1(): Promise<Result> { let p1; // Do some operations. return p1; } private async p5(): Promise<void> { // Make a call to an external API. } Some of these functions c ...

The icon for the ng-bootstrap datepicker calendar is not showing up

I recently implemented a date picker using angular-cli and ng-bootstrap. The datepicker is working perfectly after installing it from npm and adding it to the main module. However, I am facing an issue with the icon not displaying properly. Check out the ...

Unable to mock SQLite in Ionic app

I'm encountering an issue with my SQLiteMock provider not being recognized. I'm using "{ provide: SQLite, useClass: SQLiteMock }" in Ionic 3, but the SQLiteMock class is not being used instead of SQLite as expected. I have to manually specify the ...

How to retain the side menu icon in Ionic 2 even after navigating using navCtrl push

Whenever I navigate to a new page using navCtrl.push, the sidemenu icon (hamburger) disappears and is replaced by a back button instead of coexisting with it. What I am aiming for is to retain the sidemenu icon by positioning it on the right side of the i ...