Created
September 28, 2018 16:14
-
-
Save xthecapx/d608080ff3ce3b6547d6396ef72b5d77 to your computer and use it in GitHub Desktop.
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, 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