繁体   English   中英

Angular - 如何重构 *ngIf 条件?

[英]Angular - How can I refactor *ngIf condition?

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

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

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

我看到对于将显示为链接或不显示为链接的数据有重复的代码。

有什么办法可以优化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将您的 ng-template 呈现在您的 div 中,或者在我们的例子中,我们使用ng-container
  • ngTemplateOutletContext是将数据发送到ng-template的出口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM