star-rating.component.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
  2. import { FormControl } from '@angular/forms';
  3. import { CustomFieldConfigType, CustomFieldControl, SharedModule } from '@vendure/admin-ui/core';
  4. type StarType = 'empty' | 'full' | 'half';
  5. @Component({
  6. selector: 'star-rating',
  7. templateUrl: './star-rating.component.html',
  8. styleUrls: ['./star-rating.component.scss'],
  9. changeDetection: ChangeDetectionStrategy.Default,
  10. standalone: true,
  11. imports: [SharedModule],
  12. })
  13. export class StarRatingComponent implements CustomFieldControl {
  14. @Input() rating: number | null;
  15. @Input() showLabel = false;
  16. readonly: boolean;
  17. config: CustomFieldConfigType;
  18. formControl: FormControl;
  19. get starRating(): number {
  20. return this.formControl ? this.formControl.value : this.rating;
  21. }
  22. get stars(): StarType[] {
  23. const rating = this.starRating;
  24. return Array.from({ length: 5 }).map((_, i) => {
  25. const pos = i + 1;
  26. const filled = rating >= pos;
  27. if (filled) {
  28. return 'full';
  29. }
  30. if (Math.ceil(rating) < pos) {
  31. return 'empty';
  32. }
  33. return 'half';
  34. });
  35. }
  36. }