Reputation: 76
I'm trying to load a component dynamically using the ComponentResolver and ViewContainerRef services.
The child component loads ok and the template is rendered. However i want to access the inputs from the parent ('field' and 'values') inside the child component.
Any help would be much appreciated.
Parent component:
import {Component, Input, ViewChild, ComponentFactory, ViewContainerRef, ComponentResolver} from '@angular/core';
import {MyInputComponent} from './my-input.component';
@Component({
selector: 'my-field',
template: `
<label class="control-label">
<span>{{field.label}}</span>
<span class="required">*</span>
</label>
<div #target></div>
`
})
export class MyFieldComponent {
@Input() field;
@Input() values;
@ViewChild('target', { read: ViewContainerRef }) target;
ngAfterViewInit() {
this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
this.target.createComponent(factory);
});
}
constructor(public viewContainerRef: ViewContainerRef, private compiler: ComponentResolver) {
}
}
Child component:
import {Component, Input, ViewContainerRef} from '@angular/core';
@Component({
selector: 'my-input',
template: `
This is an input component!!!
`
})
export class MyInputComponent {
@Input() field: any;
@Input() values: any;
ngOnInit() {
console.log(this);
}
constructor(public viewContainerRef: ViewContainerRef) {
}
}
Upvotes: 3
Views: 773
Reputation: 214295
I think that you can leverage something like this:
this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
let component = this.target.createComponent(factory);
component.instance.field = this.field;
});
See also the example https://plnkr.co/edit/bdGYvTf8y9LEw9DAMyN1?p=preview
Upvotes: 4