title: Directive ViewContainerRef createComponent within a button
body: <p>I am trying to get a directive to create a component within the host that it is placed on, so I created this directive:</p>
  <pre class="lang-js prettyprint-override"><code>@Directive({
    selector: '[badge]',
  })
  export class BadgeDirective implements OnInit {
    constructor(
      private readonly view: ViewContainerRef
    ) {}
  
    ngOnInit() {
      this.view.createComponent(BadgeComponent);
    }
  }
  </code></pre>
  <p>Which creates this component:</p>
  <pre class="lang-js prettyprint-override"><code>@Component({
    template: '&lt;span&gt;Hello&lt;/span&gt;',
    styleUrls: ['./badge.component.scss'],
  })
  export class BadgeComponent {}
  </code></pre>
  <p>In my template where I want to use the directive (<code>AppComponent</code> for example) I have the following:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;button badge&gt;&lt;/button&gt;
  </code></pre>
  <p>Then when I load the page, the component gets created but it is outside of the button like this:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;button badge&gt;&lt;/button&gt;
  &lt;ng-component _nghost-sxr-c258=&quot;&quot;&gt;
    &lt;span&gt;Hello&lt;/span&gt;
  &lt;/ng-component&gt;
  </code></pre>
  <p>I would like to load the component within the button like this:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;button badge&gt;
    &lt;ng-component _nghost-sxr-c258=&quot;&quot;&gt;
      &lt;span&gt;Hello&lt;/span&gt;
    &lt;/ng-component&gt;
  &lt;/button&gt;
  </code></pre>
  <p>Why is it getting created outside and how can I get it to be created within the button?</p>
  <p><strong>Note:</strong> I cannot convert <code>badge</code> to a <code>Component</code> since this gets placed on existing components.</p>
  <h2>Edit</h2>
  <p>Here is one solution I found, but I am not sure I like it or if it works 100%.</p>
  <pre class="lang-js prettyprint-override"><code>  constructor(
      private readonly view: ViewContainerRef,
      private readonly el: ElementRef&lt;HTMLElement&gt;
    ) {}
  
    ngOnInit() {
      const el = this.el.nativeElement;
      const comp = this.view.createComponent(BadgeComponent);
      el.appendChild(comp.location.nativeElement);
    }
  </code></pre>