Challenge with Ahead-of-Time Compilation in Angular Dynamic Components

As part of the business logic requirements, it is necessary for me to extract the meta data from dynamic components (EntryComponents).

The approach I am taking to extract this meta data is as follows:

  1. Retrieve all components within a module using ComponentFactoryResolver
  2. Filter out classes based on Component name and specific method
  3. Instantiate the component and extract the data
  4. Destroy the component afterwards.

.

const factories = Array.from<any>(this.resolver['_factories'].keys());
console.log(factories); // Outputting all available factories

factories.forEach(element => {
  if (element.prototype.registerReportCard) { 
    temp.push(element.prototype.constructor.name);
  }
});

temp.forEach(componentName => { 
    const factoryClass = factories.find( 
      item =>
        item.prototype.registerReportCard &&
        item.prototype.constructor.name === componentName
    );
    
    const component = this.resolver
      .resolveComponentFactory(factoryClass)
      .create(this.createInjector()); 

    console.log('component', component);

    const componentMeta = component.instance[
      'componentMeta'
    ] as ReportComponentMetaInterface; 

    component.destroy(); 
  });

createInjector() {
    const staticProvider = [{ provide: [], useValue: '' }];

    return Injector.create(staticProvider);
 }

THE ISSUE

During development, the factory names are functioning correctly and match the class names of the dynamic components. https://i.sstatic.net/jDxUT.png

However, after building the project using ng build --prod. The factory names appear like this: https://i.sstatic.net/JMpGI.png

Firstly, an unknown error is occurring which I cannot identify.

Secondly, the factory class names are identical. This results in the same dynamic component being loaded multiple times (apparently 10 dynamic components).

Below is the NgModule configuration:

@NgModule({

 declarations: [
    DynamicComponentLoaderDirective,
    ContactsCreatedByDayComponent,
    ReportSkeletonComponent,
    SalesPerformanceComponent,
    TopPersonasComponent,
    ContactsOverviewComponent,
    CompaniesRevenueConversionComponent,
    ClosedCompaniesConversionComponent,
    AverageTimeCloseComponent,
    AverageTimeResponseComponent,
    ContactLifecyclePipelineComponent
  ],
  imports: [
    CommonModule,
    MatButtonModule,
    MatProgressSpinnerModule,
    ChartsModule
  ],
  entryComponents: [ContactsCreatedByDayComponent, SalesPerformanceComponent, TopPersonasComponent , ContactsOverviewComponent, CompaniesRevenueConversionComponent, ClosedCompaniesConversionComponent, AverageTimeCloseComponent, AverageTimeResponseComponent, ContactLifecyclePipelineComponent],
  exports: [DynamicComponentLoaderDirective, ReportSkeletonComponent, TopPersonasComponent, ContactsOverviewComponent, CompaniesRevenueConversionComponent, ClosedCompaniesConversionComponent, AverageTimeCloseComponent, AverageTimeResponseComponent, ContactLifecyclePipelineComponent],
  providers: [DashboardReportService]
})
export class DashboardSharedModule {}

I am unsure why this issue is happening. Can you guide me in the right direction?

Answer №1

When using the --prod flag, your code undergoes minification which results in things like "...constructor.name" becoming "a.name". This could be causing the issue you are experiencing. The underlying problem is that your code may not be compatible with minification and requires adjustments. One workaround is to configure your build without optimization (typically done in angular.json for the current Angular version). However, minification serves a purpose so it's advisable to find alternative ways to handle class names, such as passing them as string function parameters. For handling data in entryComponents, take a look at how Angular Material handles MatDialogs as entryComponents receiving MAT_DIALOG_DATA through injection: https://material.angular.io/components/dialog.

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

Guide on creating and deploying an iOS API file onto a physical device with a Mac computer

I recently switched to using a Mac and have installed Xcode successfully, along with adding the platform for iOS. However, when I use adb devices, my iPhone device is not detected, but my Android device is recognized when connected. Additionally, when ru ...

Struggling to make "Kendo UI for Angular 2" components function properly

I'm in the process of developing a prototype application that utilizes the "Kendo UI for Angular 2" controls. However, I've encountered some difficulties as only the Button control seems to be functioning correctly. The other controls either disp ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Angular2 encounters an error when processing a custom HTTP request

I offer two unique services Custom HTTP client service fetch(url):any{ this.storage.fetchData('auth-token').then((token) => { let headers = new Headers(); this.prepareHeaders(headers); return this.http.fetch(url+"?token="+toke ...

Setting key-value pairs in TypeScript objects explained

I encountered an issue with setting key/value pairs on a plain object. type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V> const getAObject: getAObjectFn = (k, v) => { return { [k]: v } } console.log(getAObject ...

Issue: Attempted to replace <package_path>.__ivy_ngcc_bak with an ngcc backup file, which is not permitted

Recently, I made the switch from Angular 8 to 9 and successfully activated Ivy by following the steps outlined here. However, upon running npm install, I encountered an error with some of my packages: Tried to overwrite <package_path>.__ivy_ngcc_bak ...

Encountering an issue while integrating React three fiber library and attempting to utilize TextGeometry

Currently, I am utilizing React in conjunction with react-three fiber and typescript in an attempt to create basic 3D text. I have encountered the following error: THREE.TextGeometry has been relocated to /examples/jsm/geometries/TextGeometry.js Below is ...

Include a <button> element in the Angular ng2-pdf-viewer framework

I am looking to showcase a PDF file on my component using ng2-pdf-viewer. One of the requirements is to include a download button that overlaps the PDF file. I have searched for references on how to achieve this but unfortunately, I haven't found any ...

Ways to dynamically configure Angular form data

Below is an Angular form group that I need help with. My goal is to initialize the form and if there is no data coming into the Input() data property, then set the form values as empty strings '' for user input. However, if there is indeed form d ...

How to implement a distinct click event for input elements containing a pipe character in Angular

I have developed an innovative Elevator application that features a unique elevator component displaying the current floor value in a box. You can see how it looks here: https://i.stack.imgur.com/h3JW5.png In order to replace the numerical floor values w ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

Encountered a WebGL context creation error when running TypeScript tests with Jest

When attempting to initialize WebGLRenderer in one of my Jest test cases, I encounter the following error: Error creating WebGL context. ...

When attempting to access Element.object3D in A-frame using TypeScript, an error stating "The 'object3D' property does not exist on the 'Element' type" is encountered

As a Japanese student, I ask for your understanding regarding my limited English proficiency. Currently, I am working on developing an a-frame library that utilizes anime.js in TypeScript to create animations. However, I encountered an issue when attemptin ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

Communicating between Angular and Node (MEAN) involves transmitting basic user information, such as email address and user ID, from Node

I've encountered an issue with the following code snippet: // Node.js router.get('/users/all', authenticate, (req, res) => { User.find({some query}).select('firstName lastName email').then((users) => { res.send(u ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

Tips for incorporating dynamic properties into TypeScript classes while ensuring accurate typing information

Within my coding project, I have a specific Users class that is being exported from the file named Users.ts export default class Users {} This Users.ts file is then exported from another file called index.ts: // classes export {default as Us ...

What could be causing the image to vanish when combining a condition with 'linear-gradient' as the value for 'background-image'?

If the variable effect is set to true, I want to display the linear-gradient effect, otherwise only show the image. picture = 'https://i.blogs.es/7c43cd/elon-musk-no-queria-ser-ceo-e-hizo-todo-lo-posible-para-evitarlo-pero-asegura-que-sin-el-tesla-mo ...