Created
August 29, 2018 05:19
-
-
Save dimpu/5768c5920510ee799c7689fac10f80bf to your computer and use it in GitHub Desktop.
Dynamic Component Creation in Angular 4+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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