I'm creating a dynamic component via the createComponent
method, and I'm having trouble getting my child
component to update it's input
values passed into it from the parent
via component.instance.prop = somevalue
method, however when I update the value in the parent
the child isn't updating it's reference.
ParentComponent:
import {
Component,
ViewChild,
ViewContainerRef,
ComponentFactoryResolver,
AfterContentInit
} from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'parent-component',
template: `
<div>
<input type="text" (keyup)="name = $event.target.value">
<span>{{ name }}</span>
</div>
<ng-container #container></ng-container>
`,
styles: []
})
export class ParentComponent implements AfterContentInit {
@ViewChild('container', { read: ViewContainerRef}) container: ViewContainerRef;
private _name = 'John Doe';
get name() {
return this._name;
}
set name(name: string) {
this._name = name;
}
constructor(private resolver: ComponentFactoryResolver) { }
ngAfterContentInit() {
let factory = this.resolver.resolveComponentFactory(ChildComponent);
let component = this.container.createComponent(factory);
component.instance.name = this.name;
}
}
ChildComponent:
import {
Component,
OnInit,
Input,
OnChanges,
SimpleChanges
} from '@angular/core';
@Component({
selector: 'child-component',
template: `
<div>
{{ name }}
</div>
`,
styles: []
})
export class ChildComponent implements OnChanges {
_name: string;
get name() {
return this._name;
}
set name(name: string) {
this._name = name;
}
constructor() { }
ngOnChanges(changes: SimpleChanges) {
console.log('onchanges ', changes);
this._name = changes.name.currentValue;
}
}
Question: How can I get a dynamic child
component created via the createComponent()
method to update it's value when the value changes in the parent
component?