New input binding for NgComponentOutlet
<p>In Angular, you can create dynamic components using the <code>NgComponentOutlet</code> 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’s look at an example to better understand this process.</p>
<p>First we need an <code>InjectionToken</code> for better type safety:</p>
<pre>
interface TitleInputs {
title: string;
subTitle: string;
}
const INPUTS = new InjectionToken<TitleInputs>('title inputs');</pre>
<p>Now in our component we can create a custom injector to set up our inputs.</p>
<pre>
@Component({
selector: 'app-root',
standalone: true,
imports: [NgComponentOutlet],
template: `
<ng-template *ngComponentOutlet="template; injector: customInjector" />
`,
})
export class AppComponent implements OnInit {
template = OldTitleComponent;
titleInputs = {
title: 'Inputs for Component outlets',
subTitle: `That's awesome`,
};
customInjector = Injector.create({
providers: [{ provide: INPUTS, useValue: this.titleInputs }],
});
}</pre>
<p>Finally, in <code>OldTitleComponent</code> , we can inject our token to retrieve our inputs.</p>
<pre>
@Component({
selector: 'app-title',
standalone: true,
template: `OldWay: {{ inputs.title }} {{ inputs.subTitle }}`,
})
export class OldTitleComponent {
inputs = inject(INPUTS);
}</pre>
<p>This solution doesn’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>