首页 > 解决方案 > 每次第一个字母更改时,将大写字母添加到角度列表中

问题描述

我有一份建筑师名单。每次建筑师以新字母开头时,我都应该添加一个字母,以构建建筑师列表:

例子:

一个

ABC建筑师北极建筑师

波士顿建筑师

D

荷兰建筑师

等等

我的实际代码:

 <ul class="architect-list">
  <li *ngFor="let architect of architects">
    <div class="single-architect" (click)="selectArchitect(architect.title)" [innerHTML]="architect.title">
    </div>
  </li>
</ul>

如何在不修改列表的情况下添加字母?

备注:字母不应链接。

标签: angular

解决方案


您可以创建一个返回布尔值的方法,以决定是否应显示占位符字母表。这应该通过将每个架构师名称的第一个字符与组件上的属性进行比较来完成。它还应确保在列表中以新字母开头的名称时立即更新该属性。

试试这个:

<ul class="architect-list">

    <ng-container *ngFor="let architect of architects">
        <ng-container *ngIf="checkIfNew(architect.title)">
            {{ architect.title.charAt(0).toUpperCase() }}
        </ng-container>
        <li>
            <div class="single-architect" (click)="selectArchitect(architect.title)" [innerHTML]="architect.title">
            </div>
        </li>
    </ng-container>
</ul>

组件类:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  currentAlphabet;
  architects = [...];

  checkIfNew(title: string) {
    if(this.currentAlphabet === title.charAt(0).toLowerCase()) {
      return false;
    } else {
      this.currentAlphabet = title.charAt(0).toLowerCase();
      return true;
    }
  }
}

这是您参考的示例 StackBlitz


推荐阅读