2017-10-10 119 views
1

我是Angular2的新手,我有一個收音機組,我試圖用[(ngModel)]綁定到實體person.testBoolean,以便我可以保存它在數據庫中。我想設置一個默認值作爲選擇,我已經看到了一些例子,發現他們將默認值設置爲[(ngModel)],但在我的情況下,我想將它綁定到我的實體,因此我不能使用[(ngModel)] 。任何人都可以提供其他選擇。 checked = idx不起作用。Angular2如何設置單選按鈕與默認值檢查

<div class="form-group"> 
    <label for="radioboolean">Boolean: </label> 
    <div *ngFor="let entry of entries; let idx = index" class="radio-inline" > 
     <input type="radio" [(ngModel)]="person.testBoolean" name="radiogroup" [checked]="idx === 1" [value]="entry.id" />{{ entry.description }} 
    </div> 
</div> 

TS碼:

entries = [ 
       {id: 1, description: 'True' }, 
       {id: 2,description: 'False'}, 
       {id: 3,description: 'Undefined'} 
      ]; 

人是我的實體:

export interface IPerson { 

    id: string; 
    name: string; 
    testNumber: number | null; 
    testDatetime: Date | null; 
    testBoolean: boolean | null; 
    // Refs to parent entities 
    team: ITeam; 
    teamId: string; 

}; 
+0

是的,這是正確的我們可以直接使用id列但它不起作用:-(,default單選按鈕仍然沒有被選中/檢查 –

回答

2

您可以使用進入這樣的ID:[checked]="entry.id === 1"

<div *ngFor="let entry of entries; let idx = index" class="radio-inline" > 
       <input type="radio" [(ngModel)]="person.testBoolean" name="radiogroup" [checked]="entry.id === 1" [value]="entry.id" />{{ entry.description }} 
      </div> 
+0

是的,這是正確的,我們可以直接使用ID列,但它沒有工作:-(,默認單選按鈕仍未被選中/檢查 –

+0

試過'[checked] =「entry.id = ==默認「'?組件中默認= this.default。 – Swoox

+0

嗨Swoox,謝謝,我如上所述,但由於某種原因「this.default」設置爲undefined,因此未選中默認單選按鈕。 打字稿文件 'default:3;' 'entries = [{id:1,description:'True'},{id:2,description:'False'},' '{id:3,description: 'Undefined'}]; ''[checked] =「entry.id === default」' –

相關問題