2017-10-06 42 views
1

我正在使用*ngIf語句,但遇到問題:else部分不執行。我不知道爲什麼,這裏是源代碼。else部分在* ngIf語句中不執行

<form [formGroup]="reviewForm" (ngSubmit)="onSubmit()"> 
    <div formArrayName="controlArray"> 
     <div class="form-group" 
      *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">  
      {{control.value}}      
      <span *ngIf="control.value!='dropdown';else addDropDown">         
       <input type="{{control.value}}" 
         class="form-control" 
         [formControlName]="i" />         
       <ng-template #addDropDown> 
        <p>hello world</p> 
        <select class="form-control"     
          [formControlName]="i"> 
        </select> 
       </ng-template> 
      </span> 
     </div> 
    </div> 
</form> 

請幫忙,謝謝。

回答

2

else條件的模板應該與@ ngIf條件相同。 當* ngIf爲false時,當前元素將從DOM中刪除。由於你的ng-template在元素中,所以它不適用於其他條件。

* ngIf else的其他工作方式的正確方法是讓模板除DOM層次結構中的* ngIf之外。

欲瞭解更多信息:https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else

在你的情況下,代碼更改爲

<!-- If Template --> 
<span *ngIf="control.value!='dropdown';else addDropDown">         
      <input 
       type="{{control.value}}" 
       class="form-control" 
       [formControlName]="i">         
</span> 

<!-- Else Template --> 
    <ng-template #addDropDown> 
       <p>hello world</p> 
       <select `enter code here` 
       class="form-control"     
       [formControlName]="i"> 
       </select> 
    </ng-template> 
+0

我相信其他模板不應該在同一水平* ngif條件,只是沒有一個兒童* ngif,因爲這個元素不可見。 https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else「模板可以在組件視圖中的任意位置定義,但通常放在ngIf後面以便可讀。」 – Wouter

+0

@Wouter:謝謝,更新了描述 –