An open API service indexing awesome lists of open source software.

https://github.com/tauhidul0821/dynamic-component-demo

Created with StackBlitz ⚡️
https://github.com/tauhidul0821/dynamic-component-demo

Last synced: 3 months ago
JSON representation

Created with StackBlitz ⚡️

Awesome Lists containing this project

README

        

## live code and web view [click here](https://stackblitz.com/~/github.com/tauhidul0821/dynamic-component-demo?file=README.MD)

```ts
// main.ts

import { Component } from "@angular/core";
import { bootstrapApplication } from "@angular/platform-browser";
import {
ViewChild,
ViewContainerRef,
ComponentFactoryResolver,
} from "@angular/core";
import { DynamicComponent } from "./app/dynamic/dynamic.component";
import { DynamicUsingFactoryResolverComponent } from "./app/dynamic-using-factory-resolver/dynamic-using-factory-resolver.component";

@Component({
selector: "app-root",
template: `

Hello from {{ name }}!


Load Component Using ComponentFactoryResolver


Load Component 2

`,
})
export class App {
name = "Angular";
@ViewChild("dynamicContainer", { read: ViewContainerRef })
container!: ViewContainerRef;
@ViewChild("dynamicContainer2", { read: ViewContainerRef })
container2!: ViewContainerRef;

constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

loadDynamicComponent(): void {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(
DynamicUsingFactoryResolverComponent
);

this.container.clear();
this.container.createComponent(componentFactory);
}

loadDynamicComponent2(): void {
this.container2.clear();
this.container2.createComponent(DynamicComponent);
}
}

bootstrapApplication(App);
```