简体   繁体   中英

How to dynamically load components in Angular 8?

Currently I'm doing it with IF, but for example in Vue.JS there is Dynamic Components . Is in Angular something similar?

<app-tabs-choice *ngIf="action.type == 'choice'"></app-tabs-choice>
<app-tabs-comment *ngIf="action.type == 'comment'"></app-tabs-comment>
<app-tabs-message *ngIf="action.type == 'message'"></app-tabs-message>

There are multiple ways to achieve it :-

  1. using ngSwitchCase

  2. you can also achieve this with routes

  3. If you have a single tab component then you can use NgTemplateOutlet to create reusable components.

In Angular there is Lazy Loading but it based on routing. In other words, you can't lazyload components based on ngIf directive, but you can lazyload them if their route is different

You can use the ngComponentOutlet , but it all depends on your use-case:

<ng-container *ngIf="tabs[action.type] as comp" [ngComponentOutlet]="comp"></ng-container>

with in your component:

export class SomeComponent {
  readonly tabs = {
    choice: TabsChoiceComponent,
    comment: TabsCommentComponent,
    message: TabsMessageComponent
  }
}

You Can Load Components Dynamically By Using Thier Name:

export class AdBannerComponent implements OnInit, OnDestroy {
  @Input() ads: AdItem[];
  currentAdIndex = -1;
  @ViewChild(AdDirective, {static: true}) adHost: AdDirective;
  interval: any;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.loadComponent();
    this.getAds();
  }

  ngOnDestroy() {
    clearInterval(this.interval);
  }

  loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    const adItem = this.ads[this.currentAdIndex];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    const viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

  getAds() {
    this.interval = setInterval(() => {
      this.loadComponent();
    }, 3000);
  }
}

Html :

<div class="ad-banner-example">
  <h3>Advertisements</h3>
  <ng-template ad-host></ng-template>
</div>

For More Information Check this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM