[英]Display clickable list items based on condition in Angular
假设我有这个我要显示的人员列表。 您将在下面看到*ngFor
循环中此迭代的HTML。 您可以查看此StackBlitz以查看完整示例。
<mat-list role="list">
<mat-list-item *ngFor="let name of names" role="listitem">
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</mat-list-item>
</mat-list>
在某些情况下 ,列表应显示为链接列表,因为人员列表然后链接到其他网页。 我能做到的是写一个*ngIf
来检查它是否应该是链表或正常列表,如下所示。
<div *ngIf="isNormalList; else isLinkedList">
<h3>Normal list with items</h3>
<mat-list role="list">
<mat-list-item *ngFor="let name of names" role="listitem">
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</mat-list-item>
</mat-list>
</div>
<ng-template #isLinkedList>
<h3>List with clickable items</h3>
<mat-list role="list">
<a mat-list-item href="#" *ngFor="let name of names" role="listitem">
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</a>
</mat-list>
</ng-template>
但是,以这种方式解决它似乎是很多重复的代码。 我也可以为列表项的内部写一个*ngIf
,但这或多或少相同,最终也会出现重复的代码。
有没有办法只在这个设置中有条件地添加a
元素?
我认为在保存线和保持可读之间存在平衡,我认为它可以克服复杂的尝试确保绝对没有代码重复。
简单易读。
<div>
<h3>List with clickable items</h3>
<mat-list role="list">
<div *ngFor="let name of names">
<a *ngIf="name.link" mat-list-item href="#" role="listitem">
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</a>
<div *ngIf="!name.link">
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</div>
</div>
</mat-list>
</div>
这将重复以下操作,添加两个新的<div>
标记。
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
这可能是我能想到的最不重复的方式,没有做一些奇怪的/ hacky,比如用它来拉伸<a>
over mat-icon
和h4
如果它存在的话。 哪个不愉快或特别易读。
这样的事情应该有效。 我认为你可以在使用$implicit
来缩短context
时使其更短,但不确定如何确切地检查Angular文档。
另外,我认为您不需要指定role
属性,材料应该为您提供这些属性。
<div>
<mat-list role="list">
<ng-container *ngIf="isNormalList; else isLinkedList">
<mat-list-item *ngFor="let name of names" role="listitem">
<ng-container *ngTemplateOutlet="listItem; context: { $implicit: name }"></ng-container>
</mat-list-item>
</ng-container>
<ng-template #isLinkedList>
<a mat-list-item href="#" *ngFor="let name of names" role="listitem">
<ng-container *ngTemplateOutlet="listItem; context: { $implicit: name }"></ng-container>
</a>
</ng-template>
</mat-list>
</div>
<ng-template #listItem let-name>
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line>{{name.firstName}}</h4>
</ng-template>
您可以将*ngFor
放在ng-template
标签上:
<ng-template ngFor [ngForOf]="items" let-item>
<div *ngIf="!item.link" class="card">
<h4>Card Info:</h4>
<p>ID: {{ item.id }}</p>
<p>
Title: {{ item.title }}
</p>
</div>
<a *ngIf="item.link" href="{{ item.link }}" class="card">
<h4>Card Info:</h4>
<p>ID: {{ item.id }}</p>
<p>
Title: {{ item.title }}
</p>
</a>
</ng-template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.