Advertisement
xapu

Untitled

Jan 4th, 2019
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Component, OnInit, ViewChild, ViewContainerRef, AfterViewInit, OnDestroy, EmbeddedViewRef, Input } from '@angular/core';
  2.  
  3. @Component({
  4.     selector: 'app-actions',
  5.     // templateUrl: './actions.component.html',
  6.     styleUrls: ['./actions.component.css'],
  7.     template: `
  8. <ng-template #pageActions>
  9.     <ng-content></ng-content>
  10. </ng-template>`
  11.  
  12. })
  13. export class ActionsComponent implements OnInit, AfterViewInit, OnDestroy {
  14.     @ViewChild('pageActions') portalActionsTmplRef;
  15.     private disposeFn: () => void;
  16.     private viewRef: EmbeddedViewRef<{}>;
  17.  
  18.     constructor(private viewContainerRef: ViewContainerRef) { }
  19.  
  20.     ngOnInit() { }
  21.  
  22.     ngAfterViewInit(): void {
  23.         // render the view
  24.         this.viewRef = this.viewContainerRef.createEmbeddedView(
  25.             this.portalActionsTmplRef
  26.         );
  27.         this.viewRef.detectChanges();
  28.  
  29.         // grab the DOM element
  30.         const outletElement = document.querySelector('#page-actions-container');
  31.  
  32.         // attach the view to the DOM element that matches our selector
  33.         this.viewRef.rootNodes.forEach(rootNode =>
  34.             outletElement.appendChild(rootNode)
  35.         );
  36.  
  37.         // register a dispose fn we can call later
  38.         // to remove the content from the DOM again
  39.         this.disposeFn = () => { };
  40.     }
  41.  
  42.     ngOnDestroy(): void {
  43.         const index = this.viewContainerRef.indexOf(this.viewRef);
  44.         if (index !== -1) {
  45.             this.viewContainerRef.remove(index);
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement