Angular - 如何重构 *ngIf 条件?

Angular - How can I refactor *ngIf condition?

在我的 angular 代码中,我设置了 2 个条件

Condition 1 - 如果 weatherService.display 为假,则将数据显示为 Link

Condition 2 - 如果 weatherService.display 为真,则不将数据显示为 Link

我看到有重复的代码用于将显示为 link 或不显示的数据。

有什么方法可以优化此 inline-edit-input> 相同的代码?

Condition 1 below (Data shown as Link)

  <a [href]="'/nature/'+lp.position+'-'+trial" *ngIf="!weatherService.display"><span>{{runLandText[i]}}</span>
  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]"
                     (saved)="runLandEdited(i)">
    <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
    </mat-form-field>
  </inline-edit-input>
  </a>

Condition 2 below (Data not shown as Link)


  <span *ngIf="weatherService.display"><span>{{runLandText[i]}}</span>
  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]"
                     (saved)="runLandEdited(i)">
    <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
    </mat-form-field>   
    </inline-edit-input>
  </span>

您可以使用 ng-templateng-container

来实现它

已创建Stackblitz Demo供您参考

Ng-模板

<ng-template #inlineEditInput let-i="index">
  <span>{{ runLandText[i] }}</span>

  <inline-edit-input id="runLand_{{i}}" [editable]="weatherService.display && runLandHasNoChildren[i]" (saved)="runLandEdited(i)">
     <mat-form-field>
      <input inlineEditTag matInput type="text" [(ngModel)]="runLandEdit[i]">
     </mat-form-field>   
  </inline-edit-input>

</ng-template>

条件#1

<a [href]="'/nature/'+lp.position+'-'+trial" *ngIf="!weatherService.display">
  <ng-container [ngTemplateOutlet]="inlineEditInput"
                [ngTemplateOutletContext]="{ index: i }"></ng-container>
</a>   

条件 #2

<span *ngIf="weatherService.display">
  <ng-container [ngTemplateOutlet]="inlineEditInput"
                [ngTemplateOutletContext]="{ index: i }"></ng-container>
</span>   

注意:

  • ngTemplateOutlet 在你的 div 中渲染你的 ng-template 或者在我们的例子中我们使用 ng-container
  • ngTemplateOutletContext 是将数据发送到 ng-template
  • 的出口