Monday, August 8, 2016

15. Create a Voter Component

voter.component.ts

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

@Component({
  selector: 'voter',
  template: `
    <div class=voter>
        <i
            class="glyphicon glyphicon-menu-up vote-button"
            [class.highlighted]="myVote == 1"
            (click)="upVote()">
        </i>
        <span class="vote-count">{{voteCount + myVote}}</span>
        <i
            class="glyphicon glyphicon-menu-down vote-button"
            [class.highlighted]="myVote == -1"
            (click)="downVote()">        
        </i>
    </div>
  <span>{{totalLikes}}</span>
  `,
  styles: [`
    .voter{
        width: 20px;
        text-align:center;
        color:#999;
    }

    .vote-count{
        font-size:1.2em
    }

    .vote-button{
        cursor:pointer;
    }

    .highlighted{

    }
  `]
})

export class VoterComponent { 
  //isFavorite = false;   // currently private, not exposed to outside
  @Input() voteCount = 0;
  @Input() myVote = 0;   
  

  @Output() vote = new EventEmitter();

  upVote(){
      if(this.myVote == 1)
        return;     // prevent double voting

      this.myVote++;
      this.vote.emit({myVote: this.myVote});
  }

  downVote(){
      if(this.myVote == -1)
        return;

      this.myVote--;
      this.vote.emit({myVote: this.myVote});
  }


app.component.ts

import { Component } from '@angular/core';
import {VoterComponent} from './voter.component'

@Component({
  moduleId: module.id,
  selector: 'app-root',
  template: `
    <voter>
      [voteCount]="post.voteCount"
      [myVote]="post.myVote"
      (vote)="onVote($event)"
    </voter>
  `,
  directives: [VoterComponent]  
})
export class AppComponent {
  post = {
    voteCount: 10,
    myVote: 0
  }

  onVote($event){
    console.log($event);
  }

}

No comments:

Post a Comment