Pouya Babaie
Pouya Babaie

Reputation: 69

Ngx-Bootstrap Rating Component dynamic value

as I'm working with this amazing component , I reached a place where I need to have a rating section. this rating section , by default have 5 stars, and a number value is coming from an Api call .

I need to make those stars filled with color yellow. for example :

if the star value is 3 :

[checked] [checked] [checked] [] [] *checked being the yellow stars and empty array being rest of the 5 stars

as i was searching for a solution , I found that ng-starring has this feature. it has a "Value" Selector which you can integrate with ngFor

valor software Ngx-bootstrap does not provide such a feature.

Upvotes: 0

Views: 719

Answers (1)

You can create A Custom Pipe:

Angular CLI Command to Create A Pipe. Type this command in your console to create a pipe:

ng g pipe pipes/transformRatingStarts

  • ng means Angular CLI
  • g means Generate
  • pipes means the folder name where the pipe will be
  • transformRatingStarts means the pipe name

Code for your pipe. A simple switch: (transform-rating-starts.pipe.ts)

    import { Pipe, PipeTransform } from '@angular/core';
...
    @Pipe({
      name: 'transformRatingStarts'
    })

    export class TransformRatingStartsPipe implements PipeTransform {

      transform(value: number): string {

      let response='';

       switch(value) {

          case:1
             reponse="[*] [] [] [] []";
             break;

          case:2
             reponse="[*] [*] [] [] []";
             break;

          case:3
             reponse="[*] [*] [*] [] []";
             break;
          
          case:4
             reponse="[*] [*] [*] [*] []";
             break;

          case:5
             reponse="[*] [*] [*] [*] [*]";
          break;

          default:
             reponse="[] [] [] [] []";
             break;

       }

        return response;

      }
    }

In your HTML, just add the pipe:

{{ yourStarValueNumericVariable | transformRatingStarts }}

NOTE:You have to import your pipe in your app.module.ts (or in the module you want to use it):

...
import { TransformRatingStartsPipe } from '.pipes/bank-name-image.pipe';
...

declarations: [
  AppComponent,
  ...
  TransformRatingStartsPipe ,
  ...
],

You always can just run the console command:

ng generate pipe pipes/transformRatingStarts

and Angular CLI will create for you the file 'transform-rating-starts.pipe.ts' with the basic structure and import it automatically into the module.

Then, you only will have to fill that pipe file with my code.

Upvotes: 1

Related Questions