Angular lesson 5: Parent component listens for child event


The child component exposes an EventEmitter property with which it emits events when something happens. The parent binds to that event property and reacts to those events.

The child’s EventEmitter property is an output property, typically adorned with an @Output decoration as seen in this StarComponent:

src/app/star/star.component.ts

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

@Component({
  selector: 'app-star',
  templateUrl: './star.component.html',
  styleUrls: ['./star.component.css']
})
export class StarComponent{
  @Input() num: number;
  @Input() hotelId: number;
  @Output() rated = new EventEmitter<number[]>();
  didRated = [0,0,0,0];

  fakeArray(num: number){
    return Array.from({length: num});
  }
  doRate(num: number, hotelId: number){
    if(this.didRated[this.hotelId]==1){
      alert('You rated this hotel');
    }else{
      this.rated.emit([num,hotelId]);
      this.didRated[this.hotelId] = 1;
      alert('Thanks for rating');
    }
  }
}

src/app/star/star.component.html

<div>
  <img *ngFor="let a of fakeArray(num); let i = index;" (click)="doRate(i,hotelId)" src="https://lh3.googleusercontent.com/-Oslq8XDO428/AAAAAAAAAAI/AAAAAAAAABM/PfJ7WdQYDcM/s640/photo.jpg" />
</div>

src/app/star/star.component.css

img{
  cursor: pointer;
}

Parent component:
src/app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Tutorialspots.com - Rated Hotels';
  rated = [-1,-1,-1,-1];
  hotels = ["Casablanca","Chicago","New York",'London'];

  onRated($event){
    console.log($event);
    this.rated[$event[1]] = $event[0];
  }
}

src/app/app.component.html

<h1>
  {{title}}
</h1>

<div *ngFor="let hotel of hotels; let id = index;" [class.rated]="rated[id]>=0">
  <div>Hotel: {{hotel}}</div>
  <div><app-star num="5" [hotelId]="id" (rated)="onRated($event)"></app-star></div>
</div>

<h2>Result:</h2>

<div *ngFor="let hotel of hotels; let id = index;">
  <div>Hotel {{hotel}}: {{rated[id]+1}} stars</div>
</div>

src/styles.css

.rated{
  opacity: 0.2;
}

Online demo: https://angular-2udcpv.stackblitz.io

angular lesson 5

Leave a Reply