title: Angular2 Dynamic Component Injection in Root
body: <h2>Question</h2>
  
  <p>I'm looking for the best approach for injecting a known/defined component into the root of an application and projecting <code>@Input()</code> options onto that component.</p>
  
  <h2>Requirement</h2>
  
  <p>This is necessary for creating things like modals/tooltips in the body of the application so that <code>overflow:hidden</code>/etc will not distort the position or cut it off completely.</p>
  
  <h2>Research</h2>
  
  <p>I've found that I can get the <code>ApplicationRef</code>'s and then hackily traverse upwards and find the <code>ViewContainerRef</code>.</p>
  
  <pre><code>constructor(private applicationRef: ApplicationRef) {
  }
  
  getRootViewContainerRef(): ViewContainerRef {
    return this.applicationRef['_rootComponents'][0]['_hostElement'].vcRef;
  }
  </code></pre>
  
  <p>once I have that I can then call <code>createComponent</code> on the ref like:</p>
  
  <pre><code>appendNextToLocation&lt;T&gt;(componentClass: Type&lt;T&gt;, location: ViewContainerRef): ComponentRef&lt;T&gt; {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
    const parentInjector = location.parentInjector;
    return location.createComponent(componentFactory, location.length, parentInjector);
  }
  </code></pre>
  
  <p>but now I've created the component but none of my <code>Input</code> properties are fulfilled. To achieve that I have to manually traverse over my options and set those on the result of <code>appendNextToLocation</code>'s instance like:</p>
  
  <pre><code>const props = Object.getOwnPropertyNames(options);
  for(const prop of props) {
    component.instance[prop] = options[prop];
  }
  </code></pre>
  
  <p>now I do realize you could do some DI to inject the options but that makes it not re-usable when trying to use as a normal component then. Heres what that looks like for reference:</p>
  
  <pre><code>let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ComponentClass);
  let parentInjector = location.parentInjector;
  
  let providers = ReflectiveInjector.resolve([
    { provide: ComponentOptionsClass, useValue: options }
  ]);
  
  childInjector = ReflectiveInjector.fromResolvedProviders(providers, parentInjector);
  
  return location.createComponent(componentFactory, location.length, childInjector);
  </code></pre>
  
  <p>all that said, all of the above actually works but it feels tad hacky at times. I'm also concerned about lifecycle timing of setting the input properties like the above since it happens after its created.</p>
  
  <h2>Notable References</h2>
  
  <ul>
  <li><a href="https://github.com/angular/angular/issues/9293" rel="noreferrer">https://github.com/angular/angular/issues/9293</a></li>
  <li><a href="https://github.com/angular/angular/issues/6446" rel="noreferrer">https://github.com/angular/angular/issues/6446</a></li>
  </ul>