skip to Main Content

I’m trying to give categories name to my chip in my Angular application. For the backend i use Spring Boot. I tried a lots to fix this error and i don’t know if is a FrontEnd problem or a BackEnd problem.
The problem is that now my categories chips appears in this way:

enter image description here

But i want name instead of numbers.

Categories are defined in .modelscategory

export enum Category {
  MANGA,
  DVD,
  LIBRI,
  COMICS
}

In .componentscategoriescategories.component.html

<div class="categories">
  <div *ngFor="let category of categories"  class="category-item">
    <div (click)="handleClick(category)">
      <app-chip
        value={{category}}
        modifier="menu-item"
        ></app-chip>
    </div>
  </div>
</div>

And this is my .ts

@Component({
  selector: 'app-categories',
  templateUrl: './categories.component.html',
  styleUrls: ['./categories.component.css']
})
export class CategoriesComponent implements OnInit {

  public categories: Category[] = [
    Category.MANGA,
    Category.DVD,
    Category.LIBRI,
    Category.COMICS
  ]


  constructor(private observableService: ObservableService) { }

  ngOnInit(): void {

  }

  handleClick(category: Category) {
    this.observableService.changeCategory(category);
  }
}

As result i want that my categories appears instead of the numbers in the chips.

2

Answers


  1. It’s issue with your enum – by default enums are numbers, starting with 0. You can just assign them whatever strings you want:

    export enum Category {
      MANGA = "MANGA",
      DVD = "DVD",
      LIBRI = "LIBRI",
      COMICS = "COMICS"
    }
    
    Login or Signup to reply.
  2. In your component’s TypeScript file (.ts), define a method to map enum values to their corresponding names:

      getCategoryName(category: Category): string {
      switch (category) {
        case Category.MANGA:
          return 'Manga';
        case Category.DVD:
          return 'DVD';
        case Category.LIBRI:
          return 'Libri';
        case Category.COMICS:
          return 'Comics';
        default:
          return '';
      }
    }
    

    In your component’s HTML file (e.g., category.component.html), use the Angular ngFor directive to iterate through the categories array and display their enum values:

      <div *ngFor="let category of categories">
      {{ getCategoryName(category) }}
    </div>
    

    However you can also maintain from backend as well.
    Here is demo:
    https://stackblitz.com/edit/stackblitz-starters-enadky?file=src%2Fmain.ts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search