Angular: How to declare a component async

Discussão em 'Angular' iniciado por Duc Trung Mai, Novembro 12, 2024.

  1. I'm trying to find a way to declare a component async and then use it in .html as normal component which is declared in declaration inside app.module

    My app.module.ts:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';

    @NgModule({
    declarations: [
    AppComponent,
    ],
    imports: [
    BrowserModule,
    ],
    providers: [],
    bootstrap: [AppComponent],
    schemas: []
    })
    export class AppModule {
    constructor() {
    this.loadComponent()
    }

    loadComponent() {
    // load and resolve FooComponent component async
    }
    }



    Then in app.component.html we can refer to the FooComponent

    <foo-component></foo-component>


    All I can find on the internet is "dynamic create component" where we have ng-template in .html file with some ref then use createComponent (or resolveComponent) API to create the FooComponent programmatically against the ref. But it's not what I expect.

    It seems to refer to an Angular component in .html file we need to put it in declaration statically at build time. Not sure how I can make it dynamically.

    Update: What I'm actually doing is, I have a lib which is used in multiple projects, the painful part is each time when the lib has new update, I need to re-run npm install for each project which is in different locations (multiple repos). Our company has adopted microfrontend (MFE) (webpack module federation) which works really well, and I'm trying to apply to the lib - converting it to MFE. Doing so, I dont need to run npm install each time my lib has update, in each MFE I simply call to the lib to get its latest update at runtime

    Please help. Thanks

    Continue reading...

Compartilhe esta Página