【问题标题】:Angular converting names to initials inside avatar角度将名称转换为头像内的首字母
【发布时间】:2021-08-18 09:57:55
【问题描述】:

我们如何将名称转换为首字母并像下面的屏幕截图中的首字母一样放入一个圆圈图标,我已经有了转换首字母的代码,现在我们如何创建并将其添加到图标中?正如您在屏幕截图中看到的那样,最大显示将是 4 个图标,然后剩余的计数将添加到图标内。

#现在这是我当前的输出,它显示名称列表,但我想像下面屏幕截图上的图标一样转换,就像一些线条头像,有什么想法吗?谢谢。

#获取姓名首字母的代码

const fullName = nameString.split(' ');
const initials = fullName.shift().charAt(0) + fullName.pop().charAt(0);
return initials.toUpperCase();

#用于显示名称的表格代码

<ng-container matColumnDef="members">
                  <mat-header-cell *matHeaderCellDef fxHide fxShow.gt-xs fxShow.gt-md mat-multi-sort-header="members"
                    class="users-table-header">
                    Members
                  </mat-header-cell>
                  <mat-cell *matCellDef="let item" fxHide fxShow.gt-xs fxShow.gt-md>
                    <div *ngFor="let member of item.teamMembersDto;let isLast=last">
                      {{member.firstName}} {{member.lastName}}{{isLast ? '' : ','}}
                    </div>
                  </mat-cell>
                </ng-container>

【问题讨论】:

  • 您是否尝试显示给定名称是带有缩写的圆形图标?
  • 是的先生,没错,​​包括距离
  • 好的,我检查一下
  • 您可能想尝试使用 name.split(" ")[0][0] 和 name.split(" ")[1][0] 来获取首字母缩写。休息是用 css 完成的。

标签: angular typescript


【解决方案1】:

首先,让我们使用 HTML 和 CSS 创建名称所需的结构

<div class="rows">
<div class="circles" *ngFor='let item of names; let i = index'>
  {{ i +1  < 4  ? getInitials(item , i) : '+'  +  (names.length - i) }}
</div>
</div>

css部分

   .rows {
  display: flex;
  align-items: center;
}
.circles{
  height: 100px;
  width: 100px;
  border-radius: 50%;
  background: #eee;
  border : 2px solid #fff;
  text-align: center;
  line-height: 100px;
  
}
.rows .circles:not(:first-child) {
margin-left: -18px;
}
.rows .circles:nth-child(n+5){
   display: none;
  }

对于 ts

    names = ['richard rick' , 'alphonse dave' , 'kilin mbappe' , 'brock lesnae' , 'kane wills' , 'Mark angel' , 'astro boy']


  getInitials(nameString , i){
    const fullName = nameString.split(' ');
const initials = fullName.shift().charAt(0) + fullName.pop().charAt(0);
return initials.toUpperCase();
  }

这是一个堆栈闪电战演示

https://stackblitz.com/edit/angular-ivy-hkd8uj?file=src%2Fapp%2Fapp.component.ts

【讨论】:

  • 无效的 stakblitz 链接
  • 不要从模板中调用 getInitials 等方法。尤其是在 *ngFor 中。它会被称为很多次。而是使用例如 rxjs 管道在模型上创建属性。
猜你喜欢
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 2018-12-12
  • 2014-11-19
相关资源
最近更新 更多