【问题标题】:Get access to child route :id访问子路由:id
【发布时间】:2019-11-24 12:48:37
【问题描述】:

我有一个子组件和它的父组件。子组件包含以下管道来订阅激活的路由:

this.route.paramMap.pipe(
  map(paramMap => +paramMap.get('id')),
  switchMap((id: number) => this.apiService.getTasks(id.toString())),
).subscribe(tasks => this.tasks = tasks);

{ path: '', component: DashboardComponent, children: [
      { path: '', redirectTo: '0', pathMatch: 'full' },
      { path: '0', component: NoListComponent },
      { path: ':id', component: ListComponent }
    ]},

如何在父组件DashboardComponent 中访问此路由 :id?

我问是因为我需要在父级内部使用相同的 id。我已经尝试通过@ViewChild 传递它,但这不会在路线更改时更新。

编辑:事件发射是不可能的,因为我正在使用路由器插座。

【问题讨论】:

标签: angular typescript


【解决方案1】:

通过router-outlet的Parent-Child组件通信是通过修改Parent组件的onActivate函数实现的,如下:

onActivate(childComponent) {
    childComponent.someEventEmitter.subscribe((data) => {
    // Will receive the data from child here 
})

子组件照常创建 EventEmitter:

export class ChildComponent {
  @Output() someEventEmitter: EventEmitter<any> = new EventEmitter();

  someFunction(data) {
    // emit data to parent component
    this.someEventEmitter.emit(data);
  }
}

在 html 中:

<button type="button" (click)="someFunction()">Do Something</button>

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 2017-07-23
    • 1970-01-01
    • 2020-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多