Leveraging Inputs Binding with NgComponentOutlet in Angular
Angular version v16.2.0 (next.4) introduced a highly practical feature — Inputs Binding with NgComponentOutlet
. In the past, when utilizing the NgComponentOutlet
directive and requiring the passage of data to the created component, developers were constrained to create a new injector and utilize it as the data provider.
Fortunately, with this new feature, we can now seamlessly pass component inputs using the inputs
input.
Component({
selector: 'foo-cmp',
standalone: true,
imports: [NgComponentOutlet],
template: ` 👇
<ng-template *ngComponentOutlet="dynamicComponent; inputs: inputs" />
`
class FooComponent {
dynamicComponent = DynamicChildComponent;
inputs = { dataProperty: 'Hello' }
}
@Component({
selector: 'app-dynamic-child',
standalone: true,
template: `{{ dataProperty }}`
})
export class DynamicChildComponent {
@Input() dataProperty: string;
}
In the example above, we pass the componentInputs
object as the value for the inputs
input. This object contains the data that we want to transmit to the dynamically created DynamicChildComponent
. The dataProperty
in FooComponent
is bound to the corresponding property in the componentInputs
object, enabling seamless data transfer.
Follow me on Medium or Twitter to read more about Angular and JS!