Skip to content

Instantly share code, notes, and snippets.

@xthecapx
Created September 28, 2018 16:14
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 xthecapx/d608080ff3ce3b6547d6396ef72b5d77 to your computer and use it in GitHub Desktop.
Save xthecapx/d608080ff3ce3b6547d6396ef72b5d77 to your computer and use it in GitHub Desktop.
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory, Input, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// Injectable Component
@Component({
selector: 'my-list',
template: '<li>{{data}}</li>'
})
export class MyItemComponent {
@Input() data;
}
// Fabric Component
@Component({
selector: 'my-factory',
template: '<ul><ng-template #myList></ng-template></ul>'
})
export class FactoryComponent implements OnInit {
// Get reference to the Container
@ViewChild('myList', { read: ViewContainerRef }) myList: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
ngOnInit() {
this.myList.clear();
// Create the component fabric
const factory: ComponentFactory<MyItemComponent> = this.resolver.resolveComponentFactory(MyItemComponent);
// Get a reference of the new component
const componentRef: ComponentRef<MyItemComponent> = this.myList.createComponent(factory);
// Pass data to the new component
componentRef.instance.data = 'name';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment