【发布时间】:2018-11-03 03:39:31
【问题描述】:
我正在通过createComponent 方法创建一个动态组件,但我无法让我的child 组件更新它的input 值,它是通过parent 通过component.instance.prop = somevalue 方法传递给它的,但是,当我更新 parent 中的值时,孩子并没有更新它的引用。
父组件:
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;
}
}
子组件:
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;
}
}
问题:如何获得通过createComponent() 方法创建的动态child 组件,以便在parent 组件中的值发生变化时更新其值?
【问题讨论】:
标签: angular