{"id":13660784,"url":"https://github.com/wesleygrimes/angular-dynamic-content","last_synced_at":"2025-04-16T03:48:43.186Z","repository":{"id":38806502,"uuid":"166105221","full_name":"wesleygrimes/angular-dynamic-content","owner":"wesleygrimes","description":"AOT Friendly Dynamic Content in Angular","archived":false,"fork":false,"pushed_at":"2023-01-04T21:34:59.000Z","size":2703,"stargazers_count":65,"open_issues_count":28,"forks_count":21,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-29T04:51:12.158Z","etag":null,"topics":["angular","angular7","dynamic","javascript","nodejs","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wesleygrimes.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-01-16T20:15:57.000Z","updated_at":"2024-06-17T05:31:21.000Z","dependencies_parsed_at":"2022-08-30T15:02:55.266Z","dependency_job_id":null,"html_url":"https://github.com/wesleygrimes/angular-dynamic-content","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wesleygrimes%2Fangular-dynamic-content","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wesleygrimes%2Fangular-dynamic-content/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wesleygrimes%2Fangular-dynamic-content/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wesleygrimes%2Fangular-dynamic-content/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wesleygrimes","download_url":"https://codeload.github.com/wesleygrimes/angular-dynamic-content/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249192439,"owners_count":21227790,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","angular7","dynamic","javascript","nodejs","typescript"],"created_at":"2024-08-02T05:01:25.698Z","updated_at":"2025-04-16T03:48:43.163Z","avatar_url":"https://github.com/wesleygrimes.png","language":"TypeScript","readme":"\u003ca href=\"https://ultimatecourses.com/topic/angular/ref/wes.grimes/\" title=\"Ultimate Courses\"\u003e\u003cimg src=\"https://ultimatecourses.com/assets/img/banners/ultimate-angular-github.svg\" alt=\"Ultimate Courses\" /\u003e\u003c/a\u003e\n\n![](https://wesleygrimes.com/assets/post_headers/dynamic_content_outlet_header.png)\n\n## Overview — Dynamic Content Outlet\n\nHave you ever needed to dynamically load content or components in your Angular applications? How about in a way that the built-in structural directives  (`*ngIf*`, `*ngSwitch`) just don’t provide? Are you also in need of the optimization benefits of using Ahead-of-Time compilation?\n\nWell, I have good news for you…(And no you don’t have to be Chuck Norris!) If you stay tuned, I will help you get a solution up and running that will provide a solid way to choose from and load dynamically, at run-time, a set of predefined modules \u0026 components in your application.\n\n\u003e This article is assumes you are building an Angular 6+ application generated using the Angular CLI. For information on using the Angular CLI check out the [official documentation](https://angular.io/cli##cli-command-reference).\n\n\u003e This arose out of a business need for the company that I work for. What’s important to note here is that many articles and examples exist on loading content dynamically in Angular, but none that I found worked reliably when compiling Angular with the `— prod` or `— aot` flags enabled. The good news is that what I describe in this article works fantastically with Ahead-of-Time compiling.\n\n## What We’re Going To Do\n\nWe’re going to build a special module with a dynamic component outlet that can be included and used anywhere in your application. The only requirement is that you register, upfront, an array mapping your dynamic components to their parent modules. You will also add these modules to the `lazyModules` property in your `angular.json` file. By doing so, the compiler will pre-compile these modules. The compiler then splits them off into separate minified chunks and makes them available to the SystemJS loader at runtime, with AOT.\n\n---\n\n## Let’s Build Our Dynamic Content Outlet\n\nAssuming that you have an existing Angular 6+ CLI generated project let’s run through the following steps to scaffold the necessary parts that make up this new Dynamic Content Outlet.\n\n### Generate the Dynamic Content Outlet Module\n\nGenerate a new module named `DynamicContentOutletModule` by running the following command in your shell of choice:\n\n```shell\n$ ng g m dynamic-content-outlet\n```\n\nWe will come back later to this module and wire things up.\n\n### Build the Dynamic Content Outlet Registry\n\nCreate a new file underneath the newly created folder `src/app/dynamic-content-outlet` named `dynamic-content-outlet.registry.ts`. This will serve as the placeholder for array mapping component name to module path and module name. For now, it will be an empty array as follows.\n\n```typescript\ninterface RegistryItem {\n  componentName: string;\n  modulePath: string;\n  moduleName: string;\n}\n\n/**\n * A registry array of Component Name to details\n * that must be updated with each new component\n * that you wish to load dynamically.\n */\n\nexport const DynamicContentOutletRegistry: RegistryItem[] = [];\n```\n\n### Build the Dynamic Content Outlet Error Component\n\nCreate a new file underneath the folder `src/app/dynamic-content-outlet/dynamic-content-outlet-error.component.ts`. This will serve as the component to be rendered anytime an error occurs attempting to load a dynamic component. You can customize the `template` property to use any custom styles or layout that you may have. The `errorMessage` input must stay the same and will be fed with the actual details of the error that occurred while attempting to dynamically render your component.\n\n```typescript\nimport { Component, Input } from '@angular/core';\n\n@Component({\n  selector: 'app-dynamic-content-outlet-error-component',\n  template: `\n    \u003cdiv\u003e{{ errorMessage }}\u003c/div\u003e\n  `\n})\nexport class DynamicContentOutletErrorComponent {\n  @Input() errorMessage: string;\n  constructor() {}\n}\n```\n\n### Build the Dynamic Content Outlet Service\n\nCreate a new file underneath the folder `src/app/dynamic-content-outlet/dynamic-content-outlet.service.ts`.\n\n- This service encapsulates the logic that loads dynamic components using SystemJS and renders them into the Dynamic Content Outlet.\n- It uses the `DynamicContentOutletRegistry` to lookup the module by `componentName`.\n- It also makes use of a new `static` property that we will add later on to each module we wish to dynamically load named `dynamicComponentsMap`. This allows us to get the type literal for the given `componentName` so that the `resolveComponentFactory` can instantiate the correct component. You might ask why we didn't just add a fourth property to the `DynamicContentOutletRegistry`, well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.\n- If an error occurs, a `DynamicContentOutletErrorComponent` is rendered instead with the error message included.\n\n```typescript\nimport {\n  ComponentFactoryResolver,\n  ComponentRef,\n  Injectable,\n  Injector,\n  NgModuleFactoryLoader,\n  Type\n} from '@angular/core';\nimport { DynamicContentOutletErrorComponent } from './dynamic-content-outlet-error.component';\nimport { DynamicContentOutletRegistry } from './dynamic-content-outlet.registry';\n\ntype ModuleWithDynamicComponents = Type\u003cany\u003e \u0026 {\n  dynamicComponentsMap: {};\n};\n\n@Injectable()\nexport class DynamicContentOutletService {\n  constructor(\n    private componentFactoryResolver: ComponentFactoryResolver,\n    private moduleLoader: NgModuleFactoryLoader,\n    private injector: Injector\n  ) {}\n\n  async GetComponent(componentName: string): Promise\u003cComponentRef\u003cany\u003e\u003e {\n    const modulePath = this.getModulePathForComponent(componentName);\n\n    if (!modulePath) {\n      return this.getDynamicContentErrorComponent(\n        `Unable to derive modulePath from component: ${componentName} in dynamic-content.registry.ts`\n      );\n    }\n\n    try {\n      const moduleFactory = await this.moduleLoader.load(modulePath);\n      const moduleReference = moduleFactory.create(this.injector);\n      const componentResolver = moduleReference.componentFactoryResolver;\n\n      const componentType = (moduleFactory.moduleType as ModuleWithDynamicComponents)\n        .dynamicComponentsMap[componentName];\n\n      const componentFactory = componentResolver.resolveComponentFactory(\n        componentType\n      );\n      return componentFactory.create(this.injector);\n    } catch (error) {\n      console.error(error.message);\n      return this.getDynamicContentErrorComponent(\n        `Unable to load module ${modulePath}.\n                Looked up using component: ${componentName}. Error Details: ${\n          error.message\n        }`\n      );\n    }\n  }\n\n  private getModulePathForComponent(componentName: string) {\n    const registryItem = DynamicContentOutletRegistry.find(\n      i =\u003e i.componentName === componentName\n    );\n\n    if (registryItem \u0026\u0026 registryItem.modulePath) {\n      // imported modules must be in the format 'path#moduleName'\n      return `${registryItem.modulePath}#${registryItem.moduleName}`;\n    }\n\n    return null;\n  }\n\n  private getDynamicContentErrorComponent(errorMessage: string) {\n    const factory = this.componentFactoryResolver.resolveComponentFactory(\n      DynamicContentOutletErrorComponent\n    );\n    const componentRef = factory.create(this.injector);\n    const instance = \u003cany\u003ecomponentRef.instance;\n    instance.errorMessage = errorMessage;\n    return componentRef;\n  }\n}\n```\n\n### Build the Dynamic Content Outlet Component\n\nCreate a new file underneath the folder `src/app/dynamic-content-outlet/dynamic-content-outlet.component.ts`. This component takes an input property named `componentName` that will call the `DynamicContentOutletService.GetComponent` method passing into it `componentName`. The service then returns an instance of that rendered and compiled component for injection into the view. The service returns an error component instance if the rendering fails for some reason. The component listens for changes via the `ngOnChanges` life-cycle method. If the `@Input() componentName: string;` is set or changes it automatically re-renders the component as necessary. It also properly handles destroying the component with the `ngOnDestroy` life-cycle method.\n\n```typescript\nimport {\n  Component,\n  ComponentRef,\n  Input,\n  OnChanges,\n  OnDestroy,\n  ViewChild,\n  ViewContainerRef\n} from '@angular/core';\nimport { DynamicContentOutletService } from './dynamic-content-outlet.service';\n\n@Component({\n  selector: 'app-dynamic-content-outlet',\n  template: `\n    \u003cng-container ##container\u003e\u003c/ng-container\u003e\n  `\n})\nexport class DynamicContentOutletComponent implements OnDestroy, OnChanges {\n  @ViewChild('container', { read: ViewContainerRef })\n  container: ViewContainerRef;\n\n  @Input() componentName: string;\n\n  private component: ComponentRef\u003c{}\u003e;\n\n  constructor(private dynamicContentService: DynamicContentOutletService) {}\n\n  async ngOnChanges() {\n    await this.renderComponent();\n  }\n\n  ngOnDestroy() {\n    this.destroyComponent();\n  }\n\n  private async renderComponent() {\n    this.destroyComponent();\n\n    this.component = await this.dynamicContentService.GetComponent(\n      this.componentName\n    );\n    this.container.insert(this.component.hostView);\n  }\n\n  private destroyComponent() {\n    if (this.component) {\n      this.component.destroy();\n      this.component = null;\n    }\n  }\n}\n```\n\n### Finish Wiring Up Parts To The Dynamic Content Outlet Module\n\nMake sure your `src/app/dynamic-content-outlet/dynamic-content-outlet.module.ts` file looks like the following:\n\n```typescript\nimport { CommonModule } from '@angular/common';\nimport {\n  NgModule,\n  NgModuleFactoryLoader,\n  SystemJsNgModuleLoader\n} from '@angular/core';\nimport { DynamicContentOutletErrorComponent } from './dynamic-content-outlet-error.component';\nimport { DynamicContentOutletComponent } from './dynamic-content-outlet.component';\nimport { DynamicContentOutletService } from './dynamic-content-outlet.service';\n\n@NgModule({\n  imports: [CommonModule],\n  declarations: [\n    DynamicContentOutletComponent,\n    DynamicContentOutletErrorComponent\n  ],\n  exports: [DynamicContentOutletComponent],\n  providers: [\n    {\n      provide: NgModuleFactoryLoader,\n      useClass: SystemJsNgModuleLoader\n    },\n    DynamicContentOutletService\n  ]\n})\nexport class DynamicContentOutletModule {}\n```\n\n---\n\n## Let’s Use Our New Dynamic Content Outlet\n\nPhew! Take a deep breath and grab a cup of coffee (french press fair trade organic dark roast). The hard work is behind you. Next we will go through the process of actually putting this new module into play!\n\n![](https://cdn-images-1.medium.com/max/1600/1*8BhahXd-DWmGj_n-mhP-gA.jpeg)\n\nFor any component that you would like dynamically rendered you need to do the following four steps. **_These steps must be followed exactly_**_._\n\n### 1. Prepare your module for dynamic import\n\n- Confirm that the component is listed in the `entryComponents` array in the module that the component is a part of.\n\n- Add to the module, a new `static` property called `dynamicComponentsMap`. This allows us to get the type literal for the given `componentName` so that the `resolveComponentFactory` can instantiate the correct component.\n\n\u003e You might ask why we didn't just add a fourth property to the `DynamicContentOutletRegistry` named `componentType`; well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.\n\nA prepared module might look as follows:\n\n```typescript\nimport { CommonModule } from '@angular/common';\nimport { NgModule } from '@angular/core';\nimport { DynamicMultipleOneComponent } from './dynamic-multiple-one.component';\nimport { DynamicMultipleTwoComponent } from './dynamic-multiple-two.component';\n\n@NgModule({\n  declarations: [MySpecialDynamicContentComponent],\n  imports: [CommonModule],\n  entryComponents: [MySpecialDynamicContentComponent]\n})\nexport class MySpecialDynamicContentModule {\n  static dynamicComponentsMap = {\n    MySpecialDynamicContentComponent\n  };\n}\n```\n\n### 2. Add your dynamic component(s) to the registry\n\nFor any component that you would like dynamically rendered, add a new entry to the `DynamicContentOutletRegistry` array in `src/app/dynamic-content-outlet/dynamic-content-outlet.registry.ts`.\n\nThe following properties must be filled out:\n\n- `componentName`: This should match exactly the name of the Component you wish to load dynamically.\n\n- `modulePath`: The absolute path to the module containing the component you wish to load dynamically. This is only the path to the module and does NOT include `moduleName` after a `#`.\n\n- `moduleName`: This is the exact name of the module.\n\n#### Example Component Mapping\n\n```typescript\n{\n  componentName: 'MySpecialDynamicContentComponent',\n  modulePath: 'src/app/my-special-dynamic-content/my-special-dynamic-content.module',\n  moduleName: 'MySpecialDynamicContentModule'\n},\n```\n\n### 3. Add your dynamic modules to the lazyModules array\n\nIn your `angular.json` update the `projects \u003e ** \u003e architect \u003e build \u003e options \u003e lazyModules` array and add an item for each module that you added to the registry in order for the Angular AOT compiler to detect and pre-compile your dynamic modules. If you have multiple projects in a folder, make sure you add this for the correct project you are importing and using dynamic modules in. The updated file will look similar to this:\n\n```json\n{\n  ...\n  \"projects\": {\n    \"angular-dynamic-content\": {\n      ...\n      \"architect\": {\n        \"build\": {\n          \"builder\": \"@angular-devkit/build-angular:browser\",\n          \"options\": {\n            ...\n            \"lazyModules\": [\"src/app/my-special-dynamic-content/my-special-dynamic-content.module\"]\n          },\n        }\n      }\n    }\n  }\n}\n```\n\n### Wire up the Dynamic Content Outlet Module\n\nUp to this point you have created your dynamic content outlet module and registered your components to be available in the outlet. The last thing we need to do is wire up our new `DynamicContentOutletModule` to be used in our application. In order to do so you need to:\n\n1. Add your new `DynamicContentOutletModule` to the `imports` array of any feature module or the main `AppModule` of your Angular application.\n\n#### Example of addition to the `imports` array\n\n```typescript\n@NgModule({\n...\nimports: [\n   ...\n   DynamicContentOutletModule\n  ],\n  ...\n})\nexport class AppModule {}\n```\n\n2. Add the following tag to the template of the parent component that you would like to render the dynamic content in:\n\n```html\n\u003capp-dynamic-content-outlet [componentName]=\"'MyComponent'\"\u003e\n\u003c/app-dynamic-content-outlet\u003e\n```\n\nThis is very similar in nature to Angular’s built-in `\u003crouter-outlet\u003e/\u003c/router-outlet\u003e` tag.\n\n3. Happy `ng serve --prod` ing!\n\n## Real-World Complex Example\n\nIf you are interested in a more in-depth real-world example, then check out the Github Repository which will demonstrate the following:\n\n- Dynamic modules with multiple components\n- Demonstrating the use of on-the-fly component changes\n- Demonstrating that the scoped styles are loaded dynamically for each component\n\n\u003e GitHub Repository Example [https://github.com/wesleygrimes/angular-dynamic-content](https://github.com/wesleygrimes/angular-dynamic-content)\n\n## Conclusion\n\nHopefully you have found this solution helpful. Here is the full GitHub repository example for you to clone and play around with. PR’s are welcome, appreciated, encouraged and accepted!\n\n## Additional Resources\n\nI would highly recommend enrolling in the Ultimate Angular courses. It is well worth the money and I have used it as a training tool for new Angular developers. Follow the link below to signup.\n\n[Ultimate Courses: Expert online courses in JavaScript, Angular, NGRX and TypeScript](https://ultimatecourses.com/?ref=76683_ttll_neb)\n\n## Special Thanks\n\nI want to take a moment and thank all those I was able to glean this information from. I did not come up with all this on my own, but I was able to get a working solution by combining parts from each of these articles!\n\n- [Dynamically Loading Components with Angular CLI](https://blog.angularindepth.com/dynamically-loading-components-with-angular-cli-92a3c69bcd28)\n\n- [Here is what you need to know about dynamic components in Angular](https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e)\n\n- [The Need for Speed Lazy Load Non-Routable Modules in Angular](https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093)\n\n- Also, a huge thank you to Medium reader [ivanwonder](https://twitter.com/ivanwond) and Github user [Milan Saraiya](https://github.com/milansar) for pointing this out and providing a fork example of resolution.\n","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwesleygrimes%2Fangular-dynamic-content","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwesleygrimes%2Fangular-dynamic-content","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwesleygrimes%2Fangular-dynamic-content/lists"}