如何在 Angular2 中将变量从 child 传递到 child

How to pass variable from child to child in Angular2

我有三个组成部分:parent(P)两个children(C1)(C2) (它们 都是 P 组件的 children 并且它们 没有嵌套 ) 在 parent 模板中看起来像

<c1-component></c1-component>
<c2-component></c2-component>

我在 C1(数字)中有一个变量 myVar,我想在 C2 组件中减少和增加它,并将该变量的新值返回给 C1(所以,我想传递的不是函数,而是变量)。我如何将此变量从 C1 传递到 C2? 我想在没有共享服务的情况下解决这个问题。

您可以使用 EventEmitter 将变量从 child1 发射到 parent。将其作为 parent 中的输入捕获,然后将其传递给选择器中的 child2。

Child 1:

import { Output } from '@angular/core';
@Output() testVariable = new EventEmitter();

在 parent 内捕获并在 Parent 内发射 html:

<c2-component [testVariable]="testVariable"></c2-component>

Child 2:

import { Input} from '@angular/core';
@Input() testVariable;