4

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

2
  • 1
    I know I could do this by writing a function in Component file, but I'm looking make this work in html itself Commented Jan 3, 2019 at 7:40
  • 1
    In this case, you can not use interpolation (only a few operations are allowed). As you say, the only way is make a function in your .ts, e.g. getChar(value:number){return String.fromCharCode(65+value)} and use as interpolation {{getChar(i)}} Commented Jan 3, 2019 at 7:45

2 Answers 2

5

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) }}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.