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

SQL Commands - essentials

  SELECT # Retrieve data from the database FROM # Specify the table to select data from WHERE # Filter rows based on a condition AS # Rename...

Best for you