Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use use string function in Angular Interpolation Tag

Tags:

angular

How to use string function in Html angular interpolation tags

In component file somevalues = [1,2,3,4,5]

Html File:

<div *ngFor="let x of somevalues; let i = index">
  {{x}} - {{i}}
  <!-- {{ String.fromCharCode(65 + i) }} -->
</div>

I would like to get results somewhat like this:

1 - 0 A
2 - 1 B
3 - 2 C
4 - 3 D
5 - 4 E

Stackblitz Link

like image 457
Chenna Avatar asked Oct 19 '25 22:10

Chenna


2 Answers

You can create a referecne of the String object in your component like:

export class AppComponent  {
 name = 'Angular';
 somevalues = [1,2,3,4,5]
 stringRef = String;
}

and then you can use this reference in the template

{{ stringRef.fromCharCode('A'.charCodeAt(0)+i) }}
like image 115
yannick Avatar answered Oct 22 '25 12:10

yannick


If you don't want to use most of the functions from String, you could simply create a function in your Component Class:

getFromCharCode(index) {
  return String.fromCharCode('A'.charCodeAt(0) + index);
}

And call it from your Template:

<div *ngFor="let x of somevalues; let i = index">
  {{x}} - {{i}}
  {{ getFromCharCode(i) }}
</div>

Here's a Working Sample StackBlitz for your ref.

like image 31
SiddAjmera Avatar answered Oct 22 '25 14:10

SiddAjmera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!