Angular根据首字母分组列表或在模板中重新分配变量的问题
创始人
2024-10-25 02:31:06
0

使用自定义管道实现根据首字母分组,并通过 *ngFor 指令在模板中重新赋值变量。

首先,在组件中定义一个用于存储数据的数组,并在 ngOnInit() 方法中初始化:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-list',
  template: `
    

{{ group.letter }}

  • {{ item.name }}
` }) export class ListComponent implements OnInit { items = [ { name: 'Apple', id: 1 }, { name: 'Banana', id: 2 }, { name: 'Cherry', id: 3 }, { name: 'Blueberry', id: 4 }, { name: 'Coconut', id: 5 }, { name: 'Grape', id: 6 }, { name: 'Kiwi', id: 7 }, { name: 'Mango', id: 8 }, { name: 'Orange', id: 9 }, { name: 'Pineapple', id: 10 } ]; groups: any[]; ngOnInit() { this.groups = this.groupByInitialLetter(this.items, 'name'); } groupByInitialLetter(array: any[], key: string): any[] { return array.reduce((groups, item) => { const group = groups.find(g => g.letter === item[key][0]); if (group) { group.items.push(item); } else { groups.push({ letter: item[key][0], items: [item] }); } return groups; }, []); } }

然后,创建一个名为 groupByLetter 的管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'groupByLetter',
  pure: false
})
export class GroupByLetterPipe implements PipeTransform {

  transform(value: any[], key: string): any[] {
    const groups = value.reduce((groups, item) => {
      const group = groups.find(g => g.letter === item[key][0]);
      if (group) {
        group.items.push(item);
      } else {
        groups.push({ letter: item[key][0], items: [item] });
      }
      return groups;
    }, []);

    return groups;
  }

}

最后,在模板中使用管道重新分配变量:

相关内容

热门资讯

今日!hhpoker德州挂真的... 今日!hhpoker德州挂真的有吗(透视)哈糖大菠萝助手(其实存在有辅助工具)-哔哩哔哩1、任何哈糖...
现场直击!wpk刷入池率脚本(... 现场直击!wpk刷入池率脚本(透视)福建天天开心辅助工具视频(都是存在有辅助辅助器)-哔哩哔哩一、福...
透视系统!aapoker怎么开... 透视系统!aapoker怎么开辅助器(透视)微乐辅助软件购买平台(总是是真的辅助修改器)-哔哩哔哩1...
推出新举措!pokemmo手机... 推出新举措!pokemmo手机版脚本(透视)中至上饶打炸辅助器开挂(一直真的有辅助app)-哔哩哔哩...
透视辅助!wepoker有没有... 透视辅助!wepoker有没有辅助(透视)葫芦娃七子连心攻略(一直真的有辅助安装)-哔哩哔哩1、下载...
于此同时!hhpoker透视脚... 于此同时!hhpoker透视脚本(透视)中至小程序破解辅助器(好像有辅助安装)-哔哩哔哩中至小程序破...
透视私人局!wpk俱乐部辅助器... 透视私人局!wpk俱乐部辅助器(透视)新上游通用卦(原来存在有辅助平台)-哔哩哔哩1、任何新上游通用...
有了最新消息!pokemmo免... 有了最新消息!pokemmo免费脚本(透视)安卓手机闲逸辅助器(其实真的有辅助平台)-哔哩哔哩1、首...
透视最新!德普之星透视辅助(透... 透视最新!德普之星透视辅助(透视)微信十三张脚本(切实真的有辅助插件)-哔哩哔哩1、完成微信十三张脚...
透视透视!wepoker轻量版... 透视透视!wepoker轻量版透视(透视)花花生活圈开挂(果然是有辅助插件)-哔哩哔哩1、游戏颠覆性...