更好的方法,如果在角度

时间:2018-03-13 00:57:47

标签: angular

我一直在网上阅读关于if else逻辑使用angular的帖子。我能够达到预期的效果,但我想知道是否还有另一种方法/更好的方法,如果有其他角度。

如果花名不是郁金香,下面的代码将打印花可用日期。如果花名是Tulip,则打印SomeOther date。

<td *ngIf ="data.FlowerName !=='Tulip'" id="someId" class="flower-detail bold">Flower Available Date: {{data.AvailableDate | date:'shortDate'}}</td>
<td *ngIf ="data.FlowerName ==='Tulip'" id="someOtherId" class="flower-detail bold">SomeOther Date: {{data.NextDate | date:'shortDate'}}</td>
<td id="some-action" class="flower-detail">
  <button id="actionTricolon" class="action-tricolon"> </button>
</td>

有没有办法以更好的方式编写它?

1 个答案:

答案 0 :(得分:1)

Angular有另外一个。这来自此处的文档:https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else

@Component({
  selector: 'ng-if-else',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show; else elseBlock">Text to show</div>
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
class NgIfElse {
  show: boolean = true;
}