Types of Communication

Input/Output:

If you have two components that should exchange data with each other, than just use the @Input() and @Output() decorator:

Here is a simple example:

  • Component that should get Data:
@Component({
selector: 'app-compa',
...
})
export class CompA{
@Input() title: string;

.....
}

--------------------
compB.component.html:

<app-compa title="Title></app-compa>

That’s it! You can now simply pass the title to CompA.

Now we want to to let an other component know, that in a specific component e.g. a button was clicked.

Here is how it works:

sendfromhere.component.ts:
@Component({ 
selector: 'app-sender',
...
})
export class SendFromHere{

@Output() clickedButton: EventEmitter = new EventEmitter();

   onClick(){
      this.clicked.emit(true);
    }
}
sendfromhere.component.html:
<button (click)="buttonClicked()"></button>

receiveButtonInfo.component.html:

<app-sender (clickedButton)="buttonClicked()"></app-sender>

receiveButtonInfo.component.ts:

@Component({ 

selector: 'app-receiver',
...
})
export class ReceiveButtonInfo{

  buttonClicked(){
    console.log("button was clicked, we know it now!");
  }
}