Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT

ng serve --prod or ng build --prod
, I can still successfully build the application. Lazy loading modules are also functioning as expected. However, when an event is triggered to load a dynamic component from the landing page, I encounter the following error:

vendor.fbd3ddffb0a9e35bbf55.bundle.js:1 ERROR Error: Uncaught (in promise): 
Error: Runtime compiler is not loaded
Error: Runtime compiler is not loaded
at Z (vendor.fbd3ddffb0a9e35bbf55.bundle.js:1)
...

<p>To resolve the above error, I applied an injector in the dynamic component like this:</p>

<pre><code>export class DynamicComponent {
private injector: Injector;
private compiler: Compiler;
constructor(injector: Injector) {
    this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS,
        injector);
    this.compiler = this.injector.get(Compiler);
}
}

After fixing the previous error, I encountered the following issue:

vendor.fbd3ddffb0a9e35bbf55.bundle.js:1 ERROR Error: Uncaught (in promise): 
Error: No NgModule metadata found for 'l'
Error: No NgModule metadata found for 'l'
at t.FDXN.t.resolve (dynamic.module.c493eec4648091b2c9b3.chunk.js:1)
...

<p>Despite extensive research on the internet and platforms like Stack Overflow, I have been unable to find a solution that works for me.</p>

<p>The structure of my dynamic component is as follows:</p>

<pre><code>import { Component, Input, Output, ViewContainerRef, Compiler, ..., }
...
@Component({
selector: 'app-dynamic-viewer',
...
})

<p>Application environment:</p>

<pre><code>@angular/cli: 1.3.0-beta.1
node: 6.9.4
os: win32 x64
@angular version: 4.3.6

If you have any workaround solutions or insights, please feel free to share. Any input would be greatly appreciated.

Answer №1

I encountered a similar issue before, and here is how I resolved it. Let's assume that you need to dynamically load the UserComponent with AOT compilation from your landing page.

User Module Configuration

@NgModule({
  ...
  entryComponents: [UserComponent]
})
export class UserModule {
  static entry = UserComponent
}

An example of your basic landing page:

Dynamic Component Template

<div>
    <ng-template #pageContainer></ng-template>
</div>    
<div *ngFor="let page of pageData">
    <div (click)="selectPage(page)">
        <div>{{page.title}}</div>
    </div>
</div>

When selecting a page on your landing page to load the component dynamically, provide the absolute path of the respective module. For the user page, the value of currentPage.modulePath could be something like

app/modules/pages/user/user.module#UserModule
. Finally, you can load your entry component as follows:

openWebApp(path: string) {
        this.systemJsNgModuleLoader.load(path)
            .then((moduleFactory: NgModuleFactory<any>) => {
                const entryComponent = (<any>moduleFactory.moduleType).entry;
                const moduleRef = moduleFactory.create(this.injector);    
                const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
                this.componentRef = this.pageHost.createComponent(compFactory);
            });
    }

The dynamic component implementation:

Dynamic Component Typescript

import { Component, Input, Output,   NgModuleFactory, ViewContainerRef, Compiler, ComponentFactory, ComponentFactoryResolver, ModuleWithComponentFactories, ComponentRef, ReflectiveInjector, SystemJsNgModuleLoader, OnInit, OnDestroy, ViewChild, Injector } from '@angular/core';
import { Http } from '@angular/http';
import { Observable, Subscription } from 'rxjs/Rx';    
import { COMPILER_PROVIDERS } from '@angular/compiler';
import * as _ from 'lodash';    
import { Page } from './interfaces/page';
import { PageService } from './services/page.service';
import { ActivePageService } from './services/active-page.service';

@Component({
    selector: 'app-dynamic-viewer',
    host: { 'class': 'template-wrapper dynamicviewer' },
    templateUrl: './dynamic.component.html',
    styleUrls: ['./dynamic.component.less'],
    providers: [PageService, ActivePageService]
})
export class DynamicComponent implements OnInit, OnDestroy {
    // Class properties and methods omitted for brevity
}

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

Executing a function simultaneously in two separate tabs using Angular

I need to conduct a specific test within my web application that requires opening two separate tabs in my browser and running the application in both tabs simultaneously. My goal is to execute the same function at the exact time in both tabs (for example, ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

What methods are available to enhance the appearance of a string with TypeScript Angular in Python?

Looking to enhance the appearance of a Python string for display on an HTML page. The string is pulled from a database and lacks formatting, appearing as a single line like so: for count in range(2): global expression; expression = 'happy'; sto ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

Incorporate an HTML span element with an onclick function bound in Angular framework

Is there a way to incorporate different icons by adding a span based on a flag, with an onclick event that triggers an internal function defined in the component ts? testfunc(){ console.log("it works") } flagToIcon(flag: boolean) { switch ( ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

Problems encountered while building TypeScript on Azure's Hosted Agent

I'm currently working on an ASP.NET MVC application built in .Net5 that utilizes TypeScript files and includes NuGet package references for the following: <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" /> ...

Error: Unable to access the 'DASH' property as it is undefined

Within my current project, I aim to showcase data related to cryptocurrencies. After making an API call, I successfully obtained a response. The specifications of my environment are as follows: Node: 8.9.5, Express: 4.16.4, Angular CLI: 7.3.6, Typescript ...

Angular 2's Implementation of Hierarchical Dependency Injection

I'm encountering a problem with my Angular 2 application. I have a root component, AppComponent, where I've injected a service called ProductService. Now, I am trying to resolve this service in one of the child components, ProductList, but I keep ...

Struggling to locate the module in React Native with TypeScript configuration

Currently, I am in the middle of transitioning our react-native project from JavaScript to TypeScript. As I attempt to import old modules, I keep encountering the following error: Cannot find module 'numeral' Oddly enough, the 'numeral&apo ...

Navigating Angular: Strategies for Managing Nested FormGroups in the HTML Template

I have recently started learning Angular and am currently working on creating a form for gathering user details. Imagine a scenario where a user can have a "friend" linked to them. This is how my FormGroup looks in a simplified version: userInformation = ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function. interface Request { ids: string[]; resolver: () => void; promise: Promise<unknown> } class Foo { public requests: ...

The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field. Here is my HTML code: <div class="date ui-input"> <input type="text" name="dateD" [ngModel]="model.date | dat ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

When utilizing useRef and useCallback in React, the output is visible in the console log but does not appear on the page

When working with API data, it's important to remember that the extraction process is asynchronous and the state may not be available at certain times. To handle this situation, we can utilize useCallback. However, even after successfully logging the ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...