本教程将指导您使用 PrimeNG 库创建全宽按钮服务列表,这些服务根据其类别进行分组。您将从示例数据中学习如何使用 Angular 和 PrimeNG 组件构建动态和用户友好的服务展示。

以下是示例数据格式:

[{"serviceId":1,"categoryId":1,"category":{"serviceCategoryId":1,"name":"sdf","nameEn":"","orderBy":0},"descriptionShort":"<p>3</p>","descriptionShortEn":"<p>3</p>","acceptInputType":"Imei","name":"c","nameEn":"","userPrice":23.00,"estimatedTime":"1","estimatedTimeEn":"1"},{"serviceId":3,"categoryId":1,"category":{"serviceCategoryId":1,"name":"sdf","nameEn":"","orderBy":0},"descriptionShort":"","descriptionShortEn":"<p>32</p>","acceptInputType":"Imei","name":"345","nameEn":"","userPrice":231.00,"estimatedTime":"213","estimatedTimeEn":""},{"serviceId":2,"categoryId":2,"category":{"serviceCategoryId":2,"name":"mk","nameEn":"","orderBy":0},"descriptionShort":"<p>-09009</p>","descriptionShortEn":"<p>099</p>","acceptInputType":"Imei","name":"090","nameEn":"","userPrice":1.00,"estimatedTime":"w2","estimatedTimeEn":""}]

每个服务都将显示为一个全宽按钮,并且相同类别的服务将放在同一个以 `category.name` 命名的 `p-panel` 中。

HTML 模板

<p-panel *ngFor="let category of categories" [header]="category.name">
  <div class="service-container">
    <button *ngFor="let service of category.services" pButton type="button" label="{{service.name}}" class="service-button"></button>
  </div>
</p-panel>

TypeScript 代码

import { Component, OnInit } from '@angular/core';
import { ListService } from './list.service';

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

  constructor(private listService: ListService) { }

  ngOnInit(): void {
    this.listService.list().subscribe((services: any[]) => {
      this.categories = this.groupServicesByCategory(services);
    });
  }

  groupServicesByCategory(services: any[]): any[] {
    const categories = [];
    services.forEach(service => {
      const categoryIndex = categories.findIndex(c => c.category.serviceCategoryId === service.category.serviceCategoryId);
      if (categoryIndex === -1) {
        categories.push({
          category: service.category,
          services: [service]
        });
      } else {
        categories[categoryIndex].services.push(service);
      }
    });
    return categories;
  }
}

CSS 样式

.service-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.service-button {
  margin: 10px;
  width: 150px;
}

在本示例中,我们使用 `*ngFor` 指令来循环遍历 `categories` 数组,并使用 `p-panel` 组件为每个类别创建一个面板。然后,我们再次使用 `*ngFor` 来循环遍历每个类别中的 `services` 数组,并使用 `pButton` 组件为每个服务创建一个按钮。

该代码展示了如何使用 PrimeNG 组件创建动态和用户友好的服务展示。


原文地址: https://www.cveoy.top/t/topic/nwyQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录