Currently I'm loading some of my components dynamically with this piece of code.
export class ComponentOutlet {
constructor(
private vcRef: ViewContainerRef,
private compiler: Compiler,
private dataService: DataService
) { }
private _createDynamicComponent() {
// Some logic to decide which component should be loaded
return MyComponent;
}
ngOnChanges() {
this.compiler.compileComponentAsync(this._createDynamicComponent())
.then(factory => {
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
this.vcRef.clear();
this.vcRef.createComponent(factory, 0, injector);
});
}
The problem is that MyComponent
has some @Input
and Output
bindings. Is it possible to set this bindings here? How can I achieve that?
The above pattern — passing data in through an “input” property and sending data out through an “output” event — is the primary way to share data between Angular 2 components.
To dynamically load the component, we use the directive as an anchor and create the component into its position in the DOM. The createComponent method requires the component type, not the instance.
If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.
Bindings to inputs and outputs can only be used to components that are statically added to another components template.
In your case you can do it imperatively like
var cmpRef = this.vcRef.createComponent(factory, 0, injector);
cmpRef.instance.someInput = value;
cmpRef.instance.someOutput.subscribe(data => this.data = data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With