我通过动态组件加载器实例化组件,一切都很好。
PARENT:
dcl.loadAsRoot(detailComponent, '#detail', injector).then(componentRef => {
componentRef.instance.item = "milano"
})
CHILD:
console.log(this) // I see here: item: "milano"
console.log(this.item) // I get: "undefined"
console.log(_.keys(this)) // I see all keys, but not the "item" key
如何在动态加载的子项中访问“this.item”?
PS。我也尝试在顶部添加@Input项,但它也不起作用。
答案 0 :(得分:0)
来自https://github.com/angular/angular/issues/6370#issuecomment-193896657
使用loadAsRoot时,您需要触发更改检测并手动连接输入,输出,注入器和组件配置功能
function onYourComponentDispose() {
}
let el = this.elementRef
let reuseInjectorOrCreateNewOne = this.injector;
this.componentLoader.loadAsRoot(YourComponent, this.elementRef, reuseInjectorOrCreateNewOne, onYourComponentDispose)
.then((compRef: ComponentRef) => {
// manually include Inputs
compRef.instance['myInputValue'] = {res: 'randomDataFromParent'};
// manually include Outputs
compRef.instance['myOutputValue'].subscribe(this.parentObserver)
// trigger change detection
cmpRef.location.internalElement.parentView.changeDetector.ref.detectChanges()
// always return in a promise
return compRef
});
另见
- https://github.com/angular/angular/issues/7453#issuecomment-193138587
- https://github.com/angular/angular/issues/6071#issuecomment-202765309