0

I have three components : parent (P) and two children (C1) and (C2) (they are both children of P component and they are not nested) in parent template it looks like

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

I have a variable myVar in C1 (number), which I want decrease and increase in C2 component and give a new value of this variable back to C1 (so, I want to pass not a function, but variable). How could I pass this variable from C1 to C2? I would like to solve this problem without shared services.

Anna F
  • 1,583
  • 4
  • 22
  • 42
  • You can try like that . (out) represent an output param using event emitter. #temp2 is a template reference variable. Create component variable var in component child 2. – ashley Jul 26 '17 at 15:59

1 Answers1

6

You could emit the variable from child1 using a EventEmitter to the parent. Catch it as an input within the parent and then pass it to child2 within the selector.

Child 1:

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

Catch within parent and emit in Parent html:

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

Child 2:

import { Input} from '@angular/core';
@Input() testVariable;
Wilcko
  • 158
  • 8
  • 1
    Please explain why this was downvoted? It is working code in my own solution. Thanks – Wilcko Jul 26 '17 at 16:04
  • I didn't downvote, but I believe it's related to because you answered a question that was marked as a duplicate, you can read how to handle duplicate question: [How should duplicate questions be handled](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) – AT82 Jul 26 '17 at 16:06
  • 1
    @Wilcko this solution is good and it's a different, thanks – Anna F Jul 26 '17 at 16:09