首页 > 解决方案 > 如何通过路由器出口将组件的输出发送到父组件

问题描述

父页面时我需要发出一个字符串

<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');
  }

标签: javascriptangularcomponentsoutput

解决方案


如果一个组件在 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();
         }
   }
}

推荐阅读