2017-02-13 40 views
0

我有/無單選按鈕,我正在讀取存儲在JSON對象中的值。首先,我正在檢查json對象是否爲空或單選按鈕的字段爲空。在這種情況下,我顯示兩個單選按鈕未選中。接下來,我正在檢查json對象中字段的真實值是否出現,如果是,請檢查yes單選按鈕,然後檢查false值並檢查no單選按鈕。看起來好像我在視圖中使用了很多相同或相似的代碼,但我想知道是否有更高效的方法來執行此操作。這是我的代碼的樣子。謝謝。有沒有更有效的方式來使用* ngIf有條件的

  <!-- json array will be empty when first coming to page, display no boxes checked --> 
      <div *ngIf="(questions | json) === '{}' || questions.partYear == null"> 
       <input type="radio" id="yesRadio" formControlName="partYear" name="partYear" value="yes" [(ngModel)]="questions.partYear">Yes<br/> 
       <input type="radio" id="noRadio" formControlName="partYear" name="partYear" value="no" [(ngModel)]="questions.partYear">No 
      </div> 

      <!-- user comes back to page, populate box that was checked during sesssion --> 
      <div *ngIf="questions?.partYear === 'yes' || questions?.partYear === true"> 
       <input type="radio" id="yesRadio" formControlName="partYear" name="partYear" value="yes" checked [(ngModel)]="questions.partYear">Yes 
      </div> 
      <div *ngIf="questions?.partYear === 'no' || questions?.partYear === false"> 
       <input type="radio" id="yesRadio" formControlName="partYear" name="partYear" value="yes" [(ngModel)]="questions.partYear">Yes 
      </div> 

      <div *ngIf="questions?.partYear === 'yes' || questions?.partYear === true"> 
       <input type="radio" id="noRadio" formControlName="partYear" name="partYear" value="no" [(ngModel)]="questions.partYear">No 
      </div> 
      <div *ngIf="questions?.partYear === 'no' || questions?.partYear === false "> 
       <input type="radio" id="noRadio" formControlName="partYear" name="partYear" value="no" checked [(ngModel)]="questions.partYear">No 
      </div> 
+0

你可能想看看[這個介紹](https://juristr.com/blog/2016/11/ng2-binding-radiobutton-lists/)Angular的單選按鈕。我會改善你的代碼的第一步是將單選按鈕1&3變成一個div,將2&4變成另一個,因爲它們似乎具有相同的'* ngIf'條件。 –

+0

你可以使用ngSwitch –

回答

0

你應該可以做這樣的事情,並且完全否定對任何* ngIf語句的需要。

<div> 
    <input type="radio" id="yesRadio" formControlName="partYear" name="partYear" [checked]="questions?.partYear === 'yes' || questions?.partYear === true" (click)="questions.partYear = 'yes'">Yes<br/> 
    <input type="radio" id="noRadio" formControlName="partYear" name="partYear" [checked]="questions?.partYear === 'no' || questions?.partYear === false" (click)="questions.partYear = 'no'">No 
</div> 
相關問題