我该如何在angular的两个子组件之间进行通信? [英] How can I communicate between two child components in angular?
问题描述
我在angular 2中非常新.我在两个组件之间进行通信时遇到问题.当我有一个包含父级组件和一些子级组件的布局时,可以很容易地使用@Input注释设置子级组件的变量.
I'm very new in angular 2. I have a problem to communicate between two components. When I have a layout with a parent and some child components, it's easy to set variables of the child components with the @Input annotation.
但是现在我有一个父组件(主要用于该布局)和两个子组件的布局:
But now I have a layout of one parent component (which is mostly for the layout) and two child components:
子组件2具有一堆按钮,这些按钮仅创建一条简单消息.现在,我想在子组件一中显示此消息.
The child component 2 have a bunch of buttons, which creates only a simple message. Now I want to display this message in child component one.
我该如何解决?预先感谢
How do I resolve it? Thanks in advance
推荐答案
您可以使用@ViewChild
和@Output
更新子组件中的属性.
You can use @ViewChild
and @Output
to update the properties in the child component.
或者,您可以使用
@Input
代替@ViewChild
.
Alternatively you can use
@Input
in place of @ViewChild
.
seidme建议的方法也可以很好地工作.这仅取决于您的用例.
The approach suggested by seidme will also work just fine. It just depends on your use case.
使用@ViewChild
和@Output
的示例:
https://plnkr.co/edit/r4KjoxLCFqkGzE1OkaQc?p=preview
使用@Input
和@Output
的示例
https://plnkr.co/edit/01iRyNSvOnOG1T03xUME?p=preview
这篇关于我该如何在angular的两个子组件之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!