title: Angular2 Dynamically add component to parent
body: <p>I have used this link to create a directive that dynamically loads a componet - <a href="http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/" rel="nofollow noreferrer">link</a>
  My problem is that I need to add the component to the parent rather than the current ViewContainer. Does anyone have any idea how I can do this?</p>
  
  <p>Background - I am loading the component dynamically within a bootstrap modal. The component is getting cut as my overflow is set to hidden. So I need to have the component outside of the modal such that I can position it over the modal.</p>
  
  <p>Here is the code for the directive</p>
  
  <pre class="lang-js prettyprint-override"><code>import {
      ComponentFactory, ComponentFactoryResolver, ComponentRef,
      Directive, ElementRef, EventEmitter,
      HostListener, Input, Output, Renderer,
      ViewContainerRef
  } from '@angular/core';
  
  import { AutoCompleteComponent } from './auto-complete.component';
  
  import { AutoComplete } from './auto-complete.model';
  import { Contact } from './contact.model';
  
  @Directive({
      selector: '[AutoComplete]'
  })
  export class AutoCompleteDirective {
  
      autoCompleteComponentRef: ComponentRef&lt;AutoCompleteComponent&gt;;
  
      @Output() onContactSelected = new EventEmitter&lt;Contact&gt;();
  
      constructor(
          private el: ElementRef,
          private viewContainer: ViewContainerRef,
          private componentFactoryResolver: ComponentFactoryResolver,
          private renderer: Renderer
      ) {
      }
  
      @HostListener('keyup') onKeyUp() {
          this.search();
      }
  
      private search()
      {
          if (this.autoCompleteComponentRef == undefined) {
              let autoCompleteComponentFactory = this.componentFactoryResolver.resolveComponentFactory(AutoCompleteComponent);
              this.autoCompleteComponentRef = this.viewContainer.createComponent(autoCompleteComponentFactory);
  
  
              this.autoCompleteComponentRef.instance.onBusinessContactSelected.subscribe((x) =&gt; {
                  this.onContactSelected.emit(x);
              })
          }
          this.autoCompleteComponentRef.instance.search(this.forename, this.surname);
  
      }
  
  }
  </code></pre>