Skip to content

Instantly share code, notes, and snippets.

@daverivera
Last active May 29, 2023 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save daverivera/454e255c4aee6aab37c03968016d2d32 to your computer and use it in GitHub Desktop.
Save daverivera/454e255c4aee6aab37c03968016d2d32 to your computer and use it in GitHub Desktop.
Dynamically add components to the DOM with Angular
import { Component, Inject, ViewContainerRef } from '@angular/core'
import { Service } from './service'
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent {
name = 'from Angular'
constructor(@Inject(Service) service, @Inject(ViewContainerRef) viewContainerRef) {
service.setRootViewContainerRef(viewContainerRef)
service.addDynamicComponent()
}
}
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { AppComponent } from './app.component'
import { Service } from './service'
import { DynamicComponent } from './dynamic.component'
@NgModule({
imports: [BrowserModule],
declarations: [
AppComponent,
DynamicComponent
],
providers: [Service],
bootstrap: [AppComponent],
entryComponents: [DynamicComponent]
})
export class AppModule { }
import { Component } from '@angular/core'
@Component({
selector: 'dynamic-component',
template: `<h2>I'm dynamically attached</h2>`
})
export class DynamicComponent { }
import {
ComponentFactoryResolver,
Injectable,
Inject,
ReflectiveInjector
} from '@angular/core'
import { DynamicComponent } from './dynamic.component'
@Injectable()
export class Service {
constructor(@Inject(ComponentFactoryResolver) factoryResolver) {
this.factoryResolver = factoryResolver
}
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef
}
addDynamicComponent() {
const factory = this.factoryResolver.resolveComponentFactory(DynamicComponent)
const component = factory.create(this.rootViewContainer.parentInjector)
this.rootViewContainer.insert(component.hostView)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment