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