Home > database >  Angular 12 - Create values with a percentage using ngFor
Angular 12 - Create values with a percentage using ngFor

Time:08-25

Hello i want to create a rating system with values in percentage. I am using Ionic 5 with Angular 12.

Here is what i am trying to do.

export class GivePointsComponent implements OnInit {
currentValue = 0;

html

<ul >
  <li *ngFor="let number of [0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%]" [class.selected]="number === currentValue">
    {{number}}
  </li>
</ul>

i am getting an error obviously about number with %

ERROR Error: Uncaught (in promise): Error: Errors during JIT compilation of template for GivePointsComponent: Parser Error: Unexpected token , at column 18 in [let number of [0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%]] in ng:///GivePointsComponent/template.html@35:10 ("
</ion-range>
<ul >
  <li [ERROR ->]*ngFor="let number of [0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%]" [class.selected]="numb"): ng:///GivePointsComponent/template.html@35:10, Parser Error: Unexpected token , at column 18 in [let number of [0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%]] in ng:///GivePointsComponent/template.html@35:10 ("li *ngFor="let number of [0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%]" [class.selected]="[ERROR ->]number === currentValue">
    {{number}}
  </li>

CodePudding user response:

just remove the percentage sign from the array and add it only for the display:

<ul >
  <li *ngFor="let number of [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" [class.selected]="number === currentValue">
    {{number}}%
  </li>
</ul>

Also I recommend you to have a property for the number list:

in TS

export class Component {
   percentList: number[] = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
   currentValue: number = 0;
}

and in Template

<ul >
  <li *ngFor="let number of percentList" [class.selected]="number === currentValue">
    {{number}}%
  </li>
</ul>

CodePudding user response:

You can either define the percentages array as strings like ['0%', '10%', ..., '100%'] or leave it as numbers [0, 10, ..., 100] and display it with {{ number '%' }}

  • Related