Mohamed Sahir
Mohamed Sahir

Reputation: 2543

How to convert number to string inside angular 2 component:

Inside the component i have

export class AppComponent implements OnInit {


public errorMsg :number =10 ;

public doughnutChartOptions: any = {
 cutoutPercentage: 85,
  elements: {
    center: {
      text: this.errorMsg + ' Energy produced in the Energy',
      fontColor: '#fff',
      fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
      fontSize: 24,
      fontStyle: 'normal'
    }
  }
};

}

  text: this.errorMsg + ' some thing',

This is a property accepted string , so here i have to pass the number to string , How to do that in angular4,typescript 2.5

Upvotes: 14

Views: 85443

Answers (5)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

Integer to string is as simple as calling .toString();

As @GünterZöchbauer said TypeScript has the same type coercion as JS, so numbers are automatically converted to strings when used in a string context

So no problem will occur same as Javascript, you can use number as string.

If you want you can do it like this so :

const num = 3;//number
const stringForm = num.toString();
console.log(stringForm);

Upvotes: 20

Gowrisankar N
Gowrisankar N

Reputation: 1

let num = 3;//number
let stringForm = num.toString();
console.log(stringForm);

Upvotes: 0

Veena K. Suresh
Veena K. Suresh

Reputation: 1002

Pls try

text:  `${this.errorMsg} Energy produced in the Energy`,

NB: Use `` (back-ticks) , instead of '' (apostrophe), to get your value.

Upvotes: 4

Deepak Jha
Deepak Jha

Reputation: 1609

It will be converted into the string automatically, for an example

class myClass{
    private myNum: number = 10;
    private myName: string = "Name Surname";
    
    onInit() {
        console.log(this.myName+this.myNum);    
    }
}

will be converted into these lines when transpiled

var myClass = /** @class */ (function () {
    function myClass() {
        this.myNum = 10;
        this.myName = "Name Surname";
    }
    myClass.prototype.onInit = function () {
        console.log(this.myName + this.myNum);
    };
    return myClass;
}());

that you can check in typescript website under play ground section,

Demo

Upvotes: 1

Eliseo
Eliseo

Reputation: 57929

you can use ''+your number

let num:number=3;
let numTxt:string=''+number;

Upvotes: 4

Related Questions