11/25/2017 - 10:14 AM

@Input() and @Output()

Parent and child components

// If the nested component wants to receive input from it's container, it must expose a property to that container
// and it can do that using @Input() decorator

// StarComponent is the nested component here
  selector: 'pm-star'
export class StarComponent {
  @Input() rating: number;

// In parent container html, pass in 'product.starRating' (parent container's property)
// to the nested component's property (rating' property of StarComponent)
    <pm-star [rating]='product.starRating'></pm-star>

// if the nested component wants to send information back to it's container
// it can raise an event and pass a payload to the container.
// In this example payload is string
// Nested component exposes an event using @Output() decorator

export class StarComponent {
  // we can declare multiple @Output() properties (with different names) to pass multiple pieces of information 
  @Output() notify: EventEmitter<string> = new EventEmitter<string>();
  onClick() {

// start.component.html
<div (click)="onClick()"> click here </div>

// container.component.html 
// $event = 'Clicked!' (the message passed from the nested component)
    <pm-star [rating]='product.starRating'

export Class ContainerComponent {
  onNotify(message: string): void {
    // do something with the 'Clicked!' message received from the star component