ngOnChange
。
http://plnkr.co/edit/MBYdMP?p=preview
Angular`` Components using ViewContainerRef.createComponent
我有两个静态组件添加到父组件,它没有任何问题。但是动态添加的组件存在输入绑定不起作用的问题,并且还没有调用export class StaticChildComp implements OnChanges {
@Input() public value: any;
@Output() public valueChange:EventEmitter = new EventEmitter();
change() {
this.valueChange.emit(this.value);
}
ngOnChanges(changes: {}): any {
console.log("From Static Child:" + JSON.stringify(changes));
}
}
@Component({
selector: 'dynamic-child-comp',
template: `
<input type="text" [(ngModel)]="value" (change)="change($event)"/>
`,
inputs: ["value"],
outpus: ["valueChange"]
})
export class DynamicChildComp extends StaticChildComp {
ngOnChanges(changes: {}): any {
console.log("From Dynamic Child:" + JSON.stringify(changes));
}
}
@Component({
selector: 'parent-comp',
template: `
<span>What Parent can see: {{value.name}}</span>
<br/>
<label>Static Child</label><child-comp [(value)]="value.name" (valueChange)="onChildValueChange($event)"></child-comp>
<br/>
<label>Dynamic Child</label><div #child></div>
`,
directives: [StaticChildComp, DynamicChildComp]
})
export class ParentComp {
@Input() value: any;
constructor(protected cr: ComponentResolver) { }
@ViewChild("child",{read: ViewContainerRef}) myChild;
ngOnInit() {
return this.cr.resolveComponent(DynamicChildComp)
.then((cf: ComponentFactory<any>) => {
let ref = this.myChild.createComponent(cf);
ref.instance.value = this.value.name;
ref.instance.valueChange.subscribe( (value: any) => {
this.onChildValueChange(value);
});
});
}
ngOnChanges (changes: {
[key: string]: SimpleChange;
}) {
console.log("Changes" + JSON.stringify(changes));
}
onChildValueChange (newValue) {
this.value.name = newValue;
}
}
方法。我还将动态组件类更新为不使用ngOnChange
,因为annotation
https://github.com/angular/angular/issues/5415中的bug
仍然没有帮助。