New input binding for NgComponentOutlet

<p>In Angular, you can create dynamic components using the&nbsp;<code>NgComponentOutlet</code>&nbsp;directive. However when your component has inputs, it was cumbersome to pass them through. In version 16.2.0-next.4, a new feature has been introduced, allowing you to bind your inputs much more easily.</p> <p>In this article, we will explore how to achieve input binding in previous versions of Angular and the new approach introduced in version 16.2.0-next.4. Additionally, we will demonstrate another method to create dynamic components.</p> <h1>Before v16.2.0-next.4</h1> <p>Prior to version 16.2.0-next.4, you had to create an injector to set up your inputs and inject it into your dynamic component to access them.</p> <p>Let&rsquo;s look at an example to better understand this process.</p> <p>First we need an&nbsp;<code>InjectionToken</code>&nbsp;for better type safety:</p> <pre> interface TitleInputs { title: string; subTitle: string; } const INPUTS = new InjectionToken&lt;TitleInputs&gt;(&#39;title inputs&#39;);</pre> <p>Now in our component we can create a custom injector to set up our inputs.</p> <pre> @Component({ selector: &#39;app-root&#39;, standalone: true, imports: [NgComponentOutlet], template: ` &lt;ng-template *ngComponentOutlet=&quot;template; injector: customInjector&quot; /&gt; `, }) export class AppComponent implements OnInit { template = OldTitleComponent; titleInputs = { title: &#39;Inputs for Component outlets&#39;, subTitle: `That&#39;s awesome`, }; customInjector = Injector.create({ providers: [{ provide: INPUTS, useValue: this.titleInputs }], }); }</pre> <p>Finally, in&nbsp;<code>OldTitleComponent</code>&nbsp;, we can inject our token to retrieve our inputs.</p> <pre> @Component({ selector: &#39;app-title&#39;, standalone: true, template: `OldWay: {{ inputs.title }} {{ inputs.subTitle }}`, }) export class OldTitleComponent { inputs = inject(INPUTS); }</pre> <p>This solution doesn&rsquo;t feel very natural but there was no other way available at that time.</p> <p><a href="https://medium.com/ngconf/new-input-binding-for-ngcomponentoutlet-cb18a86a739d">Click Here</a></p>