[Angular] Dynamic component rendering by using *ngComponentOutlet

Let's say you want to rending some component based on condition, for example a Tabs component. Inside tabs, you want to render different tab component:

<div *ngFor="let comp of comps">
  <ng-container *ngComponentOutlet="comp"></ng-container>
</div>

Generate three components by using CLI:

ng g c one
ng g c two
ng g c three

Add those componets into 'entryComponents' & 'declarations':

@NgModule({
  declarations: [
    AppComponent,
    OneComponent,
    TwoComponent,
    ThreeComponent
  ],
  imports: [
    BrowserModule,
  ],
  entryComponents: [
    OneComponent,
    TwoComponent,
    ThreeComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then we can assign those components to 'comps' variable in app.component.ts:

  comps: any[] = [
    OneComponent,
    TwoComponent,
    ThreeComponent
  ];

We can also rendering other componets form other modules, not necessary to be in the same module, we can generate a module and a component:

ng g m other
ng g c my --module other

Here we generate a 'OtherModule' and 'MyComponent' in OtherModule.

Using 'ngModuleFactory' to tell from which module you want to import the component:

<ng-container *ngComponentOutlet="OtherModuleComponent;
                                      ngModuleFactory: myModule;"></ng-container>

We need to import 'OtherModule':

@NgModule({
  declarations: [
    AppComponent,
    OneComponent,
    TwoComponent,
    ThreeComponent
  ],
  imports: [
    BrowserModule,
    OtherModule
  ],
  entryComponents: [
    OneComponent,
    TwoComponent,
    ThreeComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then in 'OtherModule', we need to add 'MyComponent' into 'entryComponents' & 'declarations':

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my/my.component';

@NgModule({
  declarations: [MyComponent],
  imports: [
    CommonModule
  ],
  entryComponents: [
    MyComponent
  ]
})
export class OtherModule { }

Now back to app.component.ts, we can declare:

import { Component, NgModuleFactory, Compiler } from '@angular/core';
import { MyComponent } from './other/my/my.component';
import { OtherModule } from './other/other.module';  

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  OtherModuleComponent = MyComponent;
  myModule: NgModuleFactory<any>;

   constructor(compiler: Compiler) {
    this.myModule = compiler.compileModuleSync(OtherModule);
  }

}

We need to inject 'Compiler' from @angular/core module, it helps to compile the module, so that we are able to get 'MyComponent' from 'OtherModule'.

That's it!

Doc

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10180922.html
今日推荐