Search code examples
angulartype-conversionstring-interpolation

Angular 2 interpolation converts number to string


I have the following component where within onClick event I am trying to increment/decrement the value of its count field. However, when I do this it convert the count field to string. I understand that interpolation convert everything to string but should not it convert string to correct type because I work with field that? Am I missing something here?

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

@Component({
  selector: 'like',
  template: `<i class="glyphicon glyphicon-heart" [class.liked]="isLiked" (click)="onClick()"></i><span>{{count}}</span>`,
  styleUrls: ['./like.component.css']
})
export class LikeComponent implements OnInit {
  @Input() isLiked: boolean;

  @Input() count: number;

  @Output() change = new EventEmitter();

  constructor() { }

  onClick() {
    console.log(typeof this.count); // <--- string

    this.isLiked = !this.isLiked;

    this.count = Number(this.count) + (this.isLiked ? 1 : -1);

    this.change.emit({value: this.isLiked});
  }

  ngOnInit() {
  }

}

Solution

  • <like count="10"></like>
    

    is like

    <like [count]="'10'"></like>
    

    so do

    <like [count]="10"></like>