![](/img/trans.png)
[英]Can I put an ngIf else condition on a Angular Material table?
[英]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-template
和ng-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>
笔记:
ng-container
ng-template
的出口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.