灯箱组件与其子组件之间的通信? [英] Communication between a lightbox component and its child component?

查看:25
本文介绍了灯箱组件与其子组件之间的通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下标记来显示灯箱中的任何组件:

I have the following markup to display any component within a lightbox:

<lightbox>
  <some-comp></some-comp>
</lightbox>

我正在尝试为两个组件之间的通信寻找更通用和 Angular 的方式(我已经阅读了 https://angular.io/guide/component-interaction).例如,子组件可能对灯箱说:

I am trying to find the more generic and Angular way for both components to communicate (I have read https://angular.io/guide/component-interaction). For instance, the child component might say to the lightbox:

  • 我的内容很大,所以你需要扩展.
  • 我包含一个表单,这里是通过表单提交的数据.

重要事项.灯箱事先不知道它将容纳哪种类型的组件.

IMPORTANT. The lightbox doesn't know in advance which type of component it will hold.

我可以通过在两个组件中注入一个服务来使其工作,并且该服务包含一个 Subject 作为两个组件之间的通信总线(此解决方案描述为 在文档中).

I can make it work by injecting a service in both components and the service contains a Subject that serves as a communication bus between the two components (this solution is described in the docs).

但是还有其他方法吗?我正在开发一个 UI 组件库,服务解决方案强制库的用户在他们在灯箱中显示的每个组件中注入和操作服务.我想避免这种情况.

But is there another way? I am developing a UI component library and the service solution forces the users of the library to inject and manipulate a service in every component they display in the lightbox. I'd like to avoid that.

(我的另一个想法是让灯箱访问其子组件并订阅该组件的特定属性,但很难以通用方式实现.)

(Another idea that I had was for the lightbox to gain access to its child component and subscribe to a specific property on that component, but it's hard to do in a generic manner.)

推荐答案

明确地将子级传递给父级

一种方法是明确地传递孩子

pass child to parent explicitly

One way would be to pass the child explicitly

  <parent [child]="child">
    <child #child></child>
  </parent>

Plunker 示例

另一种方法是在父组件上提供服务,并将其注入到子组件中.

An alternative way is to provide a service on the parent, and inject it in the child component.

Plunker 示例

最好使用 observables (BehaviorSubject, ...) 来代替 Plunker 中使用的简单字段方法.

It is better to use observables (BehaviorSubject, ...) for communication instead of the simple field approach used in the Plunker.

无论是使用父组件的开发人员,还是构建受支持的子组件的开发人员,都需要一些合作.

In every way, there is some cooperation required, either from the developer who uses the parent component, or the developer who builds supported child components.

这篇关于灯箱组件与其子组件之间的通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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