Created
September 7, 2017 20:58
-
-
Save sonukapoor/8d78f1d8b1577cb04268add8ce6cbd00 to your computer and use it in GitHub Desktop.
Creating dynamic components in angular 4
This file contains hidden or 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
| The below snippet allows us to dynamically add components into a component. | |
| // in your component.ts | |
| // contactContainer is a DOM element with a templateRef called #contactContainer | |
| @ViewChild('contactContainer', { read: ViewContainerRef }) contactContainer: ViewContainerRef; | |
| constructor( | |
| private viewContainerRef: ViewContainerRef, | |
| private componentFactoryResolver: ComponentFactoryResolver) { | |
| } | |
| ... | |
| addComponent() { | |
| // SelectComponent is the custom component | |
| const componentFactory: ComponentFactory<SelectComponent> = this.componentFactoryResolver.resolveComponentFactory(SelectComponent); | |
| let componentRef: ComponentRef<SelectComponent> = this.contactContainer.createComponent(componentFactory); | |
| // set your input parameters | |
| componentRef.instance.active = []; | |
| componentRef.instance.items = this.contacts; // some property | |
| // subscribe to output events | |
| componentRef.instance.data.subscribe((data: any) => { | |
| // some function | |
| this.setContact(data); | |
| }) | |
| componentRef.instance.placeholder = 'Type or select a contact'; | |
| } | |
| // in your html | |
| <ng-container #contactContainer></ng-container> | |
| <button (click)="addComponent">Add<button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment