2016-11-06 74 views
1

我有一個奇怪的問題,Angular 2 ngIf語句只在​​頁面上顯示一秒鐘然後消失。這是因爲我看到它,但它不想留在頁面上。猜測這是某種奇怪的同步事物。下面的代碼:Angular 2 ngIf只顯示一秒

<div class="holder"> 
<h2 *ngIf="!this.userHomeService.cards"> 
    You haven't created any cards. 
</h2> 
<div class="card-div" 
*ngFor="let c of this.userHomeService.cards"> 
    <h3 (click)="onSelect(c)">{{c.title}}</h3> 
</div> 

+1

了'ngIf'沒有停止下一條語句中,'ngFor',被顯示。你看到來自'ngFor'語句關於'this.userHomeService.cards'爲'undefined'的控制檯錯誤嗎? – Claies

+0

它看起來好像沒有顯示出來。如果我添加一張卡,那麼會出現,否則沒有任何內容。我沒有得到任何控制檯錯誤 – Linx

回答

0

你不發表您的控制器,但我能猜到它包含什麼。

  1. this.userHomeService.cards未定義或爲空。所以!this.userHomeService.cards是真的,並且「你還沒有創建任何卡。」顯示在頁面上。 ngFor不顯示任何內容,因爲沒有什麼可迭代的。
  2. 對某個異步請求(可能是HTTP請求)的響應返回,它是一個空數組。所以ngFor仍然不顯示任何內容,因爲數組是空的,但!this.userHomeService.cards變爲false,並且消息從頁面中消失。
0

您必須爲第二個div添加以避免未定義值出現任何錯誤。

<div *ngIf="this.userHomeService.cards"> 
    <div class="card-div" *ngFor="let c of this.userHomeService.cards"> 
    <h3 (click)="onSelect(c)">{{c.title}}</h3> 
    </div> 
</div> 

爲了避免在頁面上初始地顯示You haven't created any cards.消息(詭計讀取數據),你必須有某種標誌表明您的數據仍從服務器加載。例如:

<h2 *ngIf="this.finished && !this.userHomeService.cards"> 
    You haven't created any cards. 
</h2> 

而且finished變量添加到您的控制器,當您的HTTP請求完成其設置爲true。

因此,只有在數據抓取完成後纔會顯示此消息。

(這是你的問題可能的解決方案之一,最簡單的一個,我想)

+0

真的可以在同一個元素中使用'* ngIf'和'* ngFor'嗎?我不這麼認爲。 – developer033

+0

@Claies,好吧,我現在只是在相同的元素**上測試它**以及我如何懷疑它會拋出一個錯誤:'不能在一個元素上有多個模板綁定。只能使用一個名爲'template'的屬性或使用*'前綴。 – developer033

+0

@ developer033在這種情況下只使用嵌套元素(更新的答案) – phts