在Angular中,是否可以以最少的重复有条件地修改多个HTML属性?

在Angular中,是否可以以最少的重复有条件地修改多个HTML属性?,angular,Angular,我有以下Angular 9中的模板代码块,条件是显示视图(眼睛)图标或编辑(铅笔)图标。如您所见,大部分HTML都是相同的,只有少数属性和单击绑定是不同的 <button *ngIf="!(hasEditAccess$ | async)" type="button" class="icon-button" (click)="entityViewClicked()" aria-label="View&q

我有以下Angular 9中的模板代码块,条件是显示视图(眼睛)图标或编辑(铅笔)图标。如您所见,大部分HTML都是相同的,只有少数属性和单击绑定是不同的

<button *ngIf="!(hasEditAccess$ | async)" type="button" class="icon-button" (click)="entityViewClicked()" aria-label="View">
    <i class="far fa-eye" aria-hidden="true" title="View"></i>
</button>
<button *ngIf="hasEditAccess$ | async" type="button" class="icon-button" (click)="entityEditClicked()" aria-label="Edit">
    <i class="fas fa-pencil-alt" aria-hidden="true" title="Edit"></i>
</button>

在不创建新组件的情况下,有没有一种更干净的方法来编写这个HTML和条件语句一次,而不是重复这么多


我认为这可能涉及{{interpolation}}语法和某种模板变量,但我欢迎任何减少代码重复的方法。

您可以避免使用
*ngIf。。。否则

<button *ngIf="hasEditAccess$ | async; else viewButton" type="button" class="icon-button" (click)="entityEditClicked()" aria-label="Edit">
    <i class="fas fa-pencil-alt" aria-hidden="true" title="Edit"></i>
</button>
<ng-template #viewButton>
  <button type="button" class="icon-button" (click)="entityViewClicked()" aria-label="View">
      <i class="far fa-eye" aria-hidden="true" title="View"></i>
  </button>
</ng-template>

啊,我添加了一个关于使用ng容器的答案,但是我误解了你的问题。您有许多不同的属性需要更改,因此您可以在所有属性上使用一个带有条件的按钮。或者,您现在在ngIf中有两个单独的按钮。我认为这种方式可能更容易阅读。如果你在模板中多次订阅相同的内容,我也会多播可观察的内容。阿卡<代码>管道(共享())@hyperdrive我以前从未使用过
share()
操作符。我得深入研究一下。谢谢杰出的我知道
其他方面的情况,但认为这对解决复制问题没有多大帮助。但是,我不知道
,因为
关键字可以在
*ngIf
中用于创建新的变量引用。谢谢
<button *ngIf="hasEditAccess$ | async as canEdit" type="button" class="icon-button" 
  (click)="entityClicked(canEdit)" 
  [attr.aria-label]="canEdit ? 'Edit' : 'View'">
  <i aria-hidden="true" 
    [ngClass]="canEdit ? 'fas fa-pencil-alt' : 'far fa-eye'" 
    [title]="canEdit ? 'Edit' : 'View'"></i>
</button>