Skip to content

Instantly share code, notes, and snippets.

@dimpu
Created August 29, 2018 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimpu/5768c5920510ee799c7689fac10f80bf to your computer and use it in GitHub Desktop.
Save dimpu/5768c5920510ee799c7689fac10f80bf to your computer and use it in GitHub Desktop.
Dynamic Component Creation in Angular 4+
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponentService } from '../DynamicComponentService';
@Component({
selector: 'my-app',
template: `<div #container></div>`
})
export class MyAppComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
private dynamicComponentService: DynamicComponentService
) { }
ngOnInit() {
let template = `
<form>
<input type="text" [(ngModel)]="data.name" (keyup)="onNameKeyUp($event)" />
<button type="submit">Submit</button>
</form>
`
this.dynamicComponentService.addComponent(this.container, template, {
data: {},
onNameKeyUp: (event) => {
console.log(event.target.value);
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment