【问题标题】:How to send output from component via router-outlet to parent component如何通过路由器出口将组件的输出发送到父组件
【发布时间】:2021-03-22 14:48:46
【问题描述】:
我需要在什么时候发出一个字符串
父页面
<div class="container-fluid fluidy">
<router-outlet (currentpage)="componentAdded($event)"></router-outlet>
</div>
Parentpage.ts
componentAdded(stringer){
console.log(stringer);
this.currentpage = stringer;
}
子页面
@Output() currentpage = new EventEmitter<string>();
ngOnInit(): void {
this.currentpage.emit('profile');
}
【问题讨论】:
标签:
javascript
angular
components
output
【解决方案1】:
如果一个组件在 router-outlet 内启动,则它不再是具有 router-outlet 的组件的子组件。因此通常在 router-outlet 标签上有输出是行不通的。相反,您可以执行类似的操作
父组件html
<router-outlet (activate)="componentActivated($event)" (deactivate)="componentDeactivated($event)"></router-outlet>
父组件ts
componentAddedSubscription: Subscritption;
componentActivated(component) {
if(component instanceof ChildComponent) {
this.componentAddedSubscription = component.currentpage.subscribe(res=>{
//your logic
});
}
}
componentDeactivated(component) {
if(component instanceof ChildComponent) {
if(this.componentAddedSubscription?.unsubscribe) {
this.componentAddedSubscription.unsubscribe();
}
}
}