Angular 2组件到组件的通信 [英] Angular 2 component to component communication

查看:38
本文介绍了Angular 2组件到组件的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个顶部菜单(组件),它显示模型列表,还有一个侧面菜单(组件),它显示颜色列表.在页面的中心,我有一个表(组件),该表根据用户对颜色和模型控件的选择显示内容列表.这些控件都不是其他任何控件的子级.表组件呈现在路由器出口容器中.

如何使表组件侦听两个菜单组件中的属性更改?

我已经按照此处所述尝试了会话服务:

希望有帮助.

I have a top menu (Component) that displays a list of models, and a side menu (Component) that displays a list of colors. In the center of my page I have a table (Component) that displays a list of things based on the user selections of color and model controls. None of the controls is a child of any other. The table component is rendered in a router-outlet container.

How can I make the table component listen for property changes in the two menu components?

I have already tried a session service as described here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-servicehttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

It does not work because the table component is not a child of the menu components.

解决方案

I would make simple service for it:

@Injectable()
export class FilterService {
    public modelChange$:EventEmitter;
    public colorChange$:EventEmitter;

    constructor(){
        this.modelChange$ = new EventEmitter();
        this.colorChange$ = new EventEmitter();
    }

    public setModel(model):void{
        this.modelChange$.emit(model);
    }

    public setColor(color):void{
        this.colorChange$.emit(color);
    }
}

Then TopMenuComponent and SideMenuComponent will invoke the service's setters:

constructor(private _filterService:FilterService){}
// method invoked by user's action
onSelect(value) {
    this._filterService.setModel(value); // or setColor()
}

and TableComponent will subscribe for the events:

constructor(private _filterService:FilterService){
    this._filterService.modelChange$.subscribe(model => console.log("new model: " + model));
    this._filterService.colorChange$.subscribe(color => console.log("new color: " + color));
}

I used my interior artist to show how it would work:

Hope it helped.

这篇关于Angular 2组件到组件的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆