首页 > 解决方案 > Angular - 使用 routerLink 在父组件上获取事件

问题描述

我正在像这样组件父组件发出事件

子组件

export class ItemComponent {

  @Output() id = new EventEmitter()

  deleteProduct(id) {
    this.id.emit(id)
  }

}

子组件标签

<app-product-item (id)="getId($event)"></app-product-item>

在我的父组件上接收事件

getId(id){
  console.log(id)
}

这工作正常。

现在我需要具有相同的行为,但是我通过routerLink访问的组件而不是这样的标签不存在,因为我正在通过routerLink访问它。<app-product-item (id)="getId($event)"></app-product-item>

路由配置:

const routes: Routes = [
    { path: '', component: WinesComponent },
    { path: 'app-wines', component: WinesComponent },
    { path: 'app-about', component: AboutComponent },
    { path: 'app-wine-detail/:id', component: WineDetailComponent },
    { path: 'app-wine-add', component: WineAddComponent }
];

标签: angularangular2-routingrouterlink

解决方案


您可以通过服务将数据传递给您需要从中访问它的组件。

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service


推荐阅读