2016-12-21 22 views
17

như thế nào angular2 đề xuất để rendertuyên bố khác trong góc

<div *ngFor="let todo of unfinishedTodos"> 
    {{todo.title}} 
</div> 

trong trường hợp nếu unfinishedTodos.length >0

và văn bản "trống rỗng" trong những trường hợp khác.

P.S.

<div *ngIf="unfinishedTodos && unfinishedTodos.length > 0"> 
    <div *ngFor="let todo of unfinishedTodos"> 
     {{todo.title}} 
    </div> 
</div> 
<div *ngIf="!unfinishedTodos || unfinishedTodos.length <= 0"> 
    empty 
</div> 

trông xấu xí

Trả lời

25

Cú pháp tương thích với góc 4,0 và vượt quá

<ng-template #elseTemplate> 
    Content displayed if expression returns false 
</ng-template> 
<ng-container *ngIf="expression; else elseTemplate"> 
    Content displayed if expression returns true 
</ng-container> 

hoặc

<ng-container *ngIf="expression; then thenBlock; else elseBlock"></ng-container> 
<ng-template #thenBlock> 
    Content displayed if expression returns true 
</ng-template> 
<ng-template #elseBlock> 
    Content displayed if expression returns false 
</ng-template> 

Cú pháp tương thích với góc 2,0 và xa hơn nữa

<ng-container *ngIf="expression"> 
    true 
</ng-container> 
<ng-container *ngIf="!expression"> 
    else 
</ng-container> 

quan trọng

  • Bạn có thể sử dụng ví dụ: <div>, hoặc bất kỳ thẻ khác, thay vì <ng-container>

  • <template> đã bị phản đối từ 4,0 ủng hộ <ng-template> để tránh va chạm tên with already existing tag.

0

Hãy thử điều này

<div *ngFor="let todo of unfinishedTodos"> 
    {{todo.title}} 
</div> 
<div *ngIf="!unfinishedTodos?.length"> 
    empty 
</div> 
4

Với mới kiễu góc 4.0.0 Cú pháp để tuyên bố khác trông như thế này:

<div *ngIf="unfinishedTodos && unfinishedTodos.length > 0; else empty"> 
    <div *ngFor="let todo of unfinishedTodos"> 
     {{todo.title}} 
    </div> 
</div> 
<ng-template #empty> 
    empty 
</ng-template > 
+1

Là quá chậm. Một số ví dụ khác https://github.com/angular/angular/blob/aaf6e05f56c8a5493875f45af895132ea30729ad/modules/%40angular/examples/common/ngIf/ts/module.ts –

+1

Tôi hy vọng cú pháp sẽ đẹp hơn khi bản phát hành thời gian đến . –

+1

Trong Angular 4.0 '