【问题标题】:let ngIf sort elements according to their beginning letter让 ngIf 根据元素的开头字母对元素进行排序
【发布时间】:2018-08-30 20:07:57
【问题描述】:

我有一个名字列表,我想按他们的首字母对它们进行排序。因此,我编写了按钮来选择名称的第一个字母。现在我想使用 ngIf 仅显示以所选字母开头的名称。

<button *ngFor = "let letter of alphabet" (click)="showSelectedLetter(letter)">{{letter}}</button>
  <div *ngFor="let name of names">
    <button *ngIf="name.startswith(letter)"> // Pseudocode
      // only names beginning with "letter" are shown
    </button>
  </div>

我的问题,有没有类似我用来预选项目的伪代码*ngIf="name.startswith(letter)

【问题讨论】:

    标签: html angular ionic3


    【解决方案1】:

    是的,有管道的概念来对您的元素进行排序。 像使用它

    <button *ngFor = "let letter of (alphabet|sortByAlphabets)"></button>
    

    并使用ng g p sortByAlphabets 命令创建管道sortByAlphabets

    在新创建的sortByAlphabets 管道中编写您的排序逻辑。

    你的sortByAlphabets.pipe.ts 文件看起来像,

    import { Pipe, PipeTransform } from '@angular/core';
    
    import { Flyer } from './heroes';
    
    @Pipe({ name: 'sortByAlphabets' })
    export class SortByAlphabetsPipe implements PipeTransform {
      transform(array) {
        return array.sort();
      }
    }
    

    【讨论】:

      【解决方案2】:

      我为你创建了这个 Stackblitz:https://stackblitz.com/edit/angular-ujnsur

      组件.ts

        public alphabet = ['a', 'b', 'c'];
        public names = ['aname', 'bname', 'cname'];
        public selectedLetter;
      
        showSelectedLetter(letter: string) {
          this.selectedLetter = letter;
        }
      
        filterByFirstLetter(name) {
          return name.slice(0,1) === this.selectedLetter;
        }
      

      component.html

      <button *ngFor = "let letter of alphabet" (click)="showSelectedLetter(letter)">{{letter}}</button>
        <div *ngFor="let name of names">
          <div *ngIf="filterByFirstLetter(name)">
            {{name}}
          </div>
        </div>
      

      它可以满足您的要求,但对于这种类型的事情,您应该使用自定义管道:https://angular.io/guide/pipes#custom-pipes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-02
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        • 1970-01-01
        • 2018-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多