Skip to content

Instantly share code, notes, and snippets.

@sonukapoor
Created September 7, 2017 20:58
Show Gist options
  • Select an option

  • Save sonukapoor/8d78f1d8b1577cb04268add8ce6cbd00 to your computer and use it in GitHub Desktop.

Select an option

Save sonukapoor/8d78f1d8b1577cb04268add8ce6cbd00 to your computer and use it in GitHub Desktop.
Creating dynamic components in angular 4
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