我需要从动态加载的子组件向其父组件发出/冒泡事件 . 我有父组件,其中有角度标签 . 在选项卡内部,我动态加载子组件 . 由于这些是动态加载的,因此我无法将从子组件引发的事件冒泡到其父组件 .
该事件在子组件中被触发但是它没有被父级监听?
我的父组件包含选项卡如下:
<div fxLayout="column" fxLayout.gt-sm="row">
<md-tab-group class="tab-group" dynamicHeight (selectedIndexChange)="onTabChange($event)" style="width:100%; height:100%">
<md-tab *ngFor="let tab of homepageTabs; let i = index">
<ng-template mdTabLabel>{{tab.label}}</ng-template>
</md-tab>
</md-tab-group>
</div>
<div>
<div #tabContent></div>
</div>
组件代码
export class HomePageComponent implements OnInit {
private tabContentComponents = [
];
@ViewChild('tabContent', { read: ViewContainerRef })
tabContent: ViewContainerRef;
// Model for tabs
homepageTabs = [
{
label: 'HomeLabel',
tabTitle: 'HomeTitle'
},
{
label: 'App Details',
tabTitle: 'App Details'
}
];
constructor(private router: Router, private cfr: ComponentFactoryResolver) {
}
//this is the place where I am loading the child component dynamically based on some logic...
onTabChange(tabIndex) {
console.log("tabIndex : " + tabIndex);
if (tabIndex == 0) {
const factory = this.cfr.resolveComponentFactory(ApplicationListComponent);
this.tabContent.clear();
this.tabContent.createComponent(factory);
}
if (tabIndex == 1) {
const factory = this.cfr.resolveComponentFactory(ApplicationDetailsComponent);
this.tabContent.clear();
this.tabContent.createComponent(factory);
}
}
//This is the event which needs to be bubbled up from the child component
OpenReportListEvent(event: any) {
//do something here
}
}
我的孩子组件如下所示,
export class ApplicationListComponent implements OnInit {
@Output() openReportListEvent = new EventEmitter();
constructor(){
}
//This is the event which needs to emit to the parent component
OpenReportList(application: any)
{
this.openReportListEvent.emit();
}
}
在这种情况下如何将事件提升到父组件?
1 回答
我假设
this.tabContent.createComponent(factory);
返回ComponentRef,所以你基本上可以获得一个实例并直接绑定到该属性: