What are Dynamic Components in Angular?

 Question: How do you create and use dynamic components in Angular?

Answer: Dynamic components are created at runtime. You can achieve this using ComponentFactoryResolver.

Example Code:


import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';

import { DynamicComponent } from './dynamic.component';


@Component({

  selector: 'app-host',

  template: `<ng-template #dynamicComponentContainer></ng-template>`

})

export class HostComponent {

  @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) container: ViewContainerRef;


  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}


  loadDynamicComponent() {

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);

    this.container.createComponent(componentFactory);

  }

}


No comments:

Post a Comment

Angular app is taking time to load a list of data — for example, from an API call — you can enhance the user experience by showing a loading spinner Example: Show Loading Spinner While Fetching Data

  Component HTML (e.g. list.component.html ) <!-- Loading Spinner --> < div class = "text-center my-4" * ngIf = ...

Best for you