Monday, August 8, 2016

14. Create a Like Component

like.component.ts

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

@Component({
  selector: 'like',
  template: `
    <i
    class="glyphicon glyphicon-heart"
    [class.highlighted]="iLike"     
    (click)="onClick()">
  </i>
  <span>{{totalLikes}}</span>
  `,
  styles: [`
    .glyphicon-heart {
        color: #ccc; 
        cursor:pointer;
    }

    .highlighted{
        color: deeppink;
    }
  `]
})

export class LikeComponent { 
  //isFavorite = false;   // currently private, not exposed to outside
  @Input() totalLikes = 0;
  @Input() iLike = false;   
  

  onClick(){
      this.iLike = !this.iLike;
      this.totalLikes += this.iLike ? 1 : -1;
  }


app.component.html

<h1>
  {{title}}
</h1>
<like [totalLikes]="tweet.totalLikes" [iLike]="tweet.iLike"></like>

app.component.ts

import { Component } from '@angular/core';
import {LikeComponent} from './like.component'

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  directives: [LikeComponent],
  styleUrls: ['app.component.css']
})
export class AppComponent {
  tweet = {
    totalLikes: 10,
    isLike: false
  }

}



No comments:

Post a Comment