Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import { Component, OnInit, Input, ComponentFactoryResolver, ViewContainerRef, ViewChild } from '@angular/core';
  2. import { BlogPostComponentInterface } from 'app/blog-post-component-interface';
  3. import { BlogPostTypeService } from 'app/blog-post-type.service';
  4.  
  5. @Component({
  6. selector: 'app-blog-post',
  7. templateUrl: './blog-post.component.html',
  8. styleUrls: ['./blog-post.component.scss']
  9. })
  10. export class BlogPostComponent implements OnInit {
  11. @Input() post: any;
  12. @ViewChild("container", { read: ViewContainerRef }) blogPostContainer: ViewContainerRef;
  13. constructor(
  14. private componentFactoryResolver: ComponentFactoryResolver,
  15. private blogPostTypeFactory: BlogPostTypeService
  16. ) { }
  17.  
  18. loadComponent() {
  19. // use our service to get the component constructor
  20. let component = this.blogPostTypeFactory.getPostTypeFromString(this.post.type);
  21. // create a component factory with the constructor
  22. let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
  23. // clear the container contents
  24. this.blogPostContainer.clear();
  25. // create and append the component as a sibling to the container
  26. // although the Angular docs say this will append it as a child, they are LYING! :^)
  27. let componentRef = this.blogPostContainer.createComponent(componentFactory);
  28. // add the data required by the interface BlogPostComponentInterface to the component
  29. (<BlogPostComponentInterface>componentRef.instance).post = this.post;
  30. }
  31. ngOnInit() {
  32. this.loadComponent();
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement