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's new httpResource and a bonus hidden feature

  The first   release candidate   for   Angular 19.2   is out, and it includes the new experimental   httpResource . This is essentially a s...

Best for you