javascript - 如何通过路由器出口将组件的输出发送到父组件
问题描述
父页面时我需要发出一个字符串
<div class="container-fluid fluidy">
<router-outlet (currentpage)="componentAdded($event)"></router-outlet>
</div>
父页面.ts
componentAdded(stringer){
console.log(stringer);
this.currentpage = stringer;
}
子页面
@Output() currentpage = new EventEmitter<string>();
ngOnInit(): void {
this.currentpage.emit('profile');
}
解决方案
如果一个组件在 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();
}
}
}
推荐阅读
- mysql - 如何在zend framework 3中编写RLIKE?
- python - 如何用'and'替换字符串中的最后一个逗号?
- html - offset-path CSS 属性使 SVG 元素消失
- uwp - 如何更改 UWP TabViewItem 角半径?
- laravel - laravel-echo-server 使用实时 redis 服务器
- javascript - Tampermonkey 中未定义的函数
- maven - 使用 Gradle Kotlin DSL 发布 Kotlin MPP 元数据
- angular - 在 HTML 模板中调用时,默认 TS/JS 数据类型的方法会触发检测更改吗?
- php - Laravel Cashier 在 heroku 上不发送 POST 请求正文
- amazon-web-services - 具有事件模式的 Terraform AWS Cloudwatch 规则不起作用