Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. @Injectable()
  2. export class ComponentInjector {
  3.  
  4. constructor(
  5. private _injector: Injector,
  6. private _applicationRef: ApplicationRef,
  7. private _componentFactoryResolver: ComponentFactoryResolver) {
  8. }
  9.  
  10. injectComponent({componentClass, parentElement = null}) {
  11.  
  12. if (parentElement == null) {
  13. parentElement = this._applicationRef.components[0].hostView['rootNodes'][0];
  14. }
  15.  
  16. const factory = this._componentFactoryResolver.resolveComponentFactory(componentClass);
  17. const component = factory.create(this._injector);
  18.  
  19. // if you wanna create the component as a child of ur component.
  20. // component = this.viewContainerRef.createComponent(factory);
  21.  
  22. this._applicationRef.attachView(component.hostView);
  23.  
  24. parentElement.appendChild(component.hostView['rootNodes'][0]);
  25.  
  26. return component;
  27.  
  28. }
  29.  
  30. }
  31.  
  32. @Component({
  33. selector: 'wt-free',
  34. template: `
  35. <div>HELLO {{ name }}</div>
  36. `
  37. })
  38. export class DialogComponent {
  39. @Input() name = 'Foo';
  40.  
  41. ngOnChanges(changes) {
  42. console.log(changes);
  43. }
  44. }
  45.  
  46. @Component({
  47. selector: 'wt-brain',
  48. template: `
  49. <div>BRAIN</div>
  50. <button (click)="show()">SHOW</button>
  51. <button (click)="hide()">HIDE</button>
  52. `
  53. })
  54. export class BrainComponent {
  55. private dialog: ComponentRef<DialogComponent>;
  56.  
  57. constructor(private _componentInjector: ComponentInjector) {
  58. }
  59.  
  60. show() {
  61. this.dialog = this._componentInjector.injectComponent({componentClass: DialogComponent}) as ComponentRef<DialogComponent>;
  62. setInterval(() => this.dialog.instance.name += 'X', 300);
  63. }
  64.  
  65. hide() {
  66. this.dialog.destroy();
  67. }
  68.  
  69. }
  70.  
  71. // <ng-container *ngComponentOutlet="cmp"></ng-container>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement