Passing Data Between Components in Angular

     

Passing data between different components is very similar to VueJS. Both use a publisher/subscriber pattern.

Below we will demonstate how to accomplish this:

1. Create three new components: GameControl, Odd and Even


2. The GameControl Component should have buttons to start and stop the game

3. When starting the game, an event (holding a incrementing number) should get emitted each second (ref = setInterval())

gameNumber = 0; interval; constructor() {}

ngOnInit() {}

startGame() { this.interval = setInterval(() => { this.gameNumber++; this.sendNumber.emit(this.gameNumber); }, 1000); }

4. The event should be listenable from outside the component.

@Output() sendNumber = new EventEmitter();

5. When stopping the game, no more events should get emitted (clearInterval(ref))

stopGame() { clearInterval(this.interval); }

6. A new Odd component should get created for every odd number emitted, the same should happen for the Even Component (on even numbers)

@Input() element: { incrementingValue: number };

7. Simply output Odd - Number or Even - Number in the two components.

< p *ngIf=“element % 2 == false” > Odd - NUMBER < /p >

< p *ngIf=“element % 2”> even - NUMBER < /p >

8. Style the element (e.g. paragraph) holding your output text differently in both component

p { color: blue; }

comments powered by Disqus