Error when compiling TypeScript in Angular 2 due to generating dynamic components

To create dynamic components, I utilize the following method:

public addItem<T extends WidgetComponent>(ngItem: {new(): T}): T {
    let factory = this._componentFactoryResolver.resolveComponentFactory(ngItem);
    const ref = this._viewCntRef.createComponent(factory);
    const newItem: T = ref.instance as T;
    ...
    return newItem;
  }

The method can be called in this manner:

const ref: MyWidgetComponent = this.dashboard.addItem<MyWidgetComponent>(MyWidgetComponent);

However, TypeScript is showing a compilation error:

app.component.ts:45:35 
Untyped function calls may not accept type arguments.

I attempted to replace {new(): T} with Type<T>, but the same error persists:

app.component.ts:45:35 
Untyped function calls may not accept type arguments.

What would be the correct definition in this scenario? Despite the compilation error, the code functions perfectly...

EDIT: For those interested, here is the complete code snippet https://github.com/jaumard/ng2-dashboard/blob/master/components/dashboard/dashboard.component.ts#L99

Answer №1

I was able to successfully resolve the compilation error by updating the method signature to:

public addItem(ngItem: Type<WidgetComponent>): WidgetComponent

After making this change, I adjusted the call to:

const ref: MyWidgetComponent = this.dashboard.addItem(MyWidgetComponent) as MyWidgetComponent;

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

typescript missing return type in array.map

Why does TypeScript allow the code below, despite it containing a type error that I would expect? export interface Structure { aaa: string; } export function f1(): Structure[] { // TypeScript is fine with this, but not me const result = [].map(c ...

Incorporating an AngularJs App into Joomla: A Step-by-

As someone who is currently learning both Angular and Joomla, I am curious about the possibility of integrating an Angular JS Application within Joomla. While Joomla is known for its ease in creating articles and managing content through the admin panel, i ...

Struggling to update the value of matAutocomplete in Angular

Could someone please assist me? I am currently working on reactive forms and utilizing matAutocomplete for element searches. I have set up a subscription to listen for changes in my input in order to search for specific items. However, I am facing an issue ...

When attempting to utilize TypeScript with Storybook, Jest may encounter an error stating, "Incompatible types for property 'id'."

Currently, I'm exploring the use of stories in my unit tests with Jest + RTL to reduce redundancy. However, I've encountered an error stating "Types of property 'id' are incompatible" when passing arguments that are also used in my stor ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

Changing the Date Display format of a new Date() instance

Just starting out with the MEAN Stack I'm currently utilizing the new date() function to retrieve the date, but I prefer not to display the time offset. ...

Integrate a fully developed ReactJS 16.x application seamlessly into an existing AngularJS 1.x framework

On a current project I'm working on, there's a unique challenge where I need to incorporate a compiled ReactJS app into an existing AngularJS project, with the Chrome/Firefox browser serving as the end-user interface. This setup isn't ideal, ...

Utilize Angular-Material to showcase a tooltip when hovering over a form label

I am struggling to display a tooltip on a label. Is there an easy fix for this issue? <mat-form-field> <mat-label matTooltip="Please enter your E-Mail Address"> E-Mail <mat-icon>help_outline</mat-icon> < ...

Limit the TypeScript generic to a specific key that corresponds to a property of another generic

I currently have a setup with various interfaces and objects as outlined below: interface ServicesList { [key: string]: Service; } interface Service { uuid: string; characteristics: CharacteristictList; } interface CharacteristictList { [ ...

What could be causing the interface to malfunction when defining a type that includes an enum as a property key?

When dealing with an enum and wanting to use its values as keys in objects, the type declaration looks like this: enum Bar { A, B } let dictionary: BarDictType = { [Bar.A]: "foo", [Bar.B]: "bar" } type BarDictType = { ...

AngularFire's $requireAuth function is failing to recognize expired authentication

After conducting some research on this issue, I came across this link. It led me to believe that the problem shouldn't exist, so I must be making a mistake somewhere. I just can't seem to figure it out. Every now and then, when I visit my app af ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

Contrasting @Input with Dependency Injection in Angular 10

Is there a way to pass values from a parent component to a child component without using the @Input decorator? I'm thinking about creating an instance of the Parent class in the constructor (Dependency Injection) and then accessing the variable value ...

How to Determine the Requirement Status of Input Variables in an Angular 2 Directive?

Is it possible to specify an input variable in a directive as required or optionally as non-required? In the example below, we have set a default value of false. However, if I fail to declare it in the parent component template, ng2 AoT throws an error: ...

Error in Angular CLI: Unable to locate module when utilizing a bespoke library formed with 'ng new library'

After using the Angular CLI to create my own library with ng new library lib-name, I attempted to consume it. However, when trying to import the library as instructed: import {MyLibModule} from 'ngx-mylib'; I encountered the error message: er ...

Using AngularJS to dynamically bind HTML content based on a variable’s value

I am trying to dynamically display an image of a man or a woman on a scene, depending on the gender of the person logged into my website. The ng-bind-html directive is working fine when I define "imageToLoad" statically. However, it fails when I try to gen ...

the behavior subject remains static and does not update

Working on setting my language in the BehaviorSubject with a default value using a LanguageService. The service structure is as follows import {Injectable} from '@angular/core'; import * as globals from '../../../environments/globals'; ...

Developing a login feature in Angular 2 using Spring Security

I am currently in the process of integrating Spring Security with a custom Angular 2 login. Specifically, I have set up an endpoint in my application that is protected by Spring Security. If someone tries to access this endpoint, they will be redirected to ...

Extract item from the collection

I am struggling with the following code: app.controller('modalController', function($scope, $http,$modalInstance, $rootScope, items){ // Retrieving information $http.post('/ajax/bundle', {'items':items}).success(functi ...

How can a specific condition be used to remove an Object from an Array stored in localStorage?

I've saved some data in localStorage, for example: $localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1},{'id':3 ...