Skip to content

Instantly share code, notes, and snippets.

@aniketmuruskar
Created August 6, 2022 12:43
Show Gist options
  • Save aniketmuruskar/adc2de326ae2eb5c71688a7ec7ca4f62 to your computer and use it in GitHub Desktop.
Save aniketmuruskar/adc2de326ae2eb5c71688a7ec7ca4f62 to your computer and use it in GitHub Desktop.
Host component typescript file
import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild } from '@angular/core';
import { AddComponent } from '../add.component';
import { AppComponentHostDirective } from '../app-component-host.directive';
@Component({
selector: 'app-ui-builder',
templateUrl: './app-ui-builder.component.html',
styleUrls: []
})
export class AppUIBuilderComponent implements OnInit, OnDestroy, OnChanges {
@Input() components!: AddComponent[];
@ViewChild(AppComponentHostDirective, { static: true, read: AppComponentHostDirective })
componentHost!: AppComponentHostDirective;
constructor() {}
ngOnChanges(changes: SimpleChanges): void {
this.buildComponents();
}
ngOnInit(): void {
this.buildComponents();
}
private buildComponents() {
this.componentHost.viewContainerRef.clear();
for (const component of this.components) {
if (!!component) {
const viewContainerRef = this.componentHost.viewContainerRef;
const componentRef = viewContainerRef.createComponent<AddComponent>(component.component);
componentRef.instance.config = component.config;
componentRef.instance.data = component.config.data;
}
}
}
ngOnDestroy(): void {
this.components = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment