Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, Input, ComponentFactoryResolver, ViewContainerRef, ViewChild } from '@angular/core';
- import { BlogPostComponentInterface } from 'app/blog-post-component-interface';
- import { BlogPostTypeService } from 'app/blog-post-type.service';
- @Component({
- selector: 'app-blog-post',
- templateUrl: './blog-post.component.html',
- styleUrls: ['./blog-post.component.scss']
- })
- export class BlogPostComponent implements OnInit {
- @Input() post: any;
- @ViewChild("container", { read: ViewContainerRef }) blogPostContainer: ViewContainerRef;
- constructor(
- private componentFactoryResolver: ComponentFactoryResolver,
- private blogPostTypeFactory: BlogPostTypeService
- ) { }
- loadComponent() {
- // use our service to get the component constructor
- let component = this.blogPostTypeFactory.getPostTypeFromString(this.post.type);
- // create a component factory with the constructor
- let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
- // clear the container contents
- this.blogPostContainer.clear();
- // create and append the component as a sibling to the container
- // although the Angular docs say this will append it as a child, they are LYING! :^)
- let componentRef = this.blogPostContainer.createComponent(componentFactory);
- // add the data required by the interface BlogPostComponentInterface to the component
- (<BlogPostComponentInterface>componentRef.instance).post = this.post;
- }
- ngOnInit() {
- this.loadComponent();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement