Jamie Barker
Jamie Barker

Reputation: 183

Angular 2 - components communication

I'm new to Angular2 and I'm trying to get my head around @Input and @Output type thing.

As an example I have two components. I want a button in component one to toggle the visibility of component two.

import { Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
selector: 'widget-one',
template:'<div class="widget-one" (click)="sendToWidgetTwo()"><button>Send to widget two</button></div>'})

export class WidgetOne {

  constructor(){
    console.log('Hello Widget One');
  }

  sendToWidgetTwo(){
    console.log("button clicked");
    // communicate with widget two
  }

}

import { Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'widget-two',
  template:'<div *ngIf="showing" class="widget-two">{{msg}}</div>' 
})
export class WidgetTwo {

  msg = "hello widget two";
  showing = true;

  constructor(){
    console.log('Hello Widget Two');
  }

}

I want WidgetOne's button to toggle WidgetTwo's showing variable to show or hide it.

Upvotes: 1

Views: 370

Answers (1)

Yakov Fain
Yakov Fain

Reputation: 12376

If both components have a common parent, the first component should emit an event that would set a boolean var in the parent to toggle the visibility of the second component. In the template of the parent use the *ngIf directive bound to this boolean variable to show/hide the component two. I've recorded a short video to show how to implement inter-component communication using the parent component as a mediator here: https://www.youtube.com/watch?v=tSXx4NoKEYY&t=3s

Upvotes: 2

Related Questions