如何从 Angular 中的子路由组件访问父组件属性?

问题描述:

我是 Angular 的新手,我被困在那里.我知道如何简单地通过注入 [parentData]="var" 来在父组件和子组件之间共享数据.进入子选择器 <>.

I'm new to Angular and I'm stuck there. I know how to share data between parent and child components simply by injecting [parentData]="var" into the child selector <>.

但是当使用路由时;我只有一个路由器插座,无法将 [parentData] 绑定到它,因为它会引发错误.

But when using routing; I only have a router-outlet and can't bind [parentData] to it as it throws an error.

从子路径访问父属性的最佳和最简单的方法是什么?

What is the best and easiest way to access parent properties from a child's route?

该项目位于stackblitz 此处.

我需要在子组件中显示产品(来自父组件).

I need to display products (from the parent component) inside the child component.

版本:(Angular 5)

version:(Angular 5)

是的,这很简单,当你想传递给 router-outlet 中的组件时,你需要使用 服务,实际上该组件在你去正确的路径之前并不存在于模板中,所以通常的绑定在这里不起作用.

Yes this is pretty simple, when you want to pass to component that are in router-outlet you need to use services, actually that component do not exist in the template before you go to the right path, so usual bindings don't work here.

所以解决这个问题的最好方法是创建一些简单的服务

So the best way to work this around is to create some simple service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataTransferService {

  private products= new BehaviorSubject<any>([]);
  cast= this.products.asObservable();

  sendAnything(data) {
    this.products.next(data);
  }

}

然后将您的服务注入到父组件和子组件的构造函数中

then inject your service into both constructors of your parent and child component

 constructor(private dataTransfer: DataTransferService){}

然后创建一个方法

 shareData(data){
    this.dataTransfer.sendAnything(data) // to send something
}

并从 parent.component.html 中调用它

and call it from the parent.component.html with

(click)="shareData(data)" // data is the parent data that you want to share

在子组件中

在 ngOnInit 方法中添加:

In child component

inside the ngOnInit method add:

 ngOnInit() {
   this.dataTransfer.products.subscribe(res=> this.var = res) // var is the property that you want to assign the data to it.
 }

获取数据并使用它.
更多信息和示例您可以在 doc