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

CPU vs GPU Architecture

  CPU vs GPU Architecture CPU (Central Processing Unit) and GPU (Graphics Processing Unit) have distinct architectural differences, optimize...

Best for you