Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 how to set radio button as checked with a default value

I am new to Angular2, I have a radio group and I am trying to bind it using [(ngModel)] to entity person.testBoolean so that I can save it in the database. I want to set a default value as selected and I have seen few examples and found that they set the default value to [(ngModel)] but in my case I want to bind it to my entity hence I cannot use [(ngModel)]. Can anybody advise alternative options. checked = idx does not work.

<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 code:

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

Person is my entity:

export interface IPerson {

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

};
like image 284
Auo Avatar asked Dec 13 '22 20:12

Auo


2 Answers

You can use the id of entry like this: [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>
like image 129
Swoox Avatar answered Dec 29 '22 08:12

Swoox


If you always want the first item to be selected you can use.

In your loop, *ngFor="let entry of entries; let first = first;

and in your radio button group - [checked] = "first"

for example:

<div *ngFor="let entry of entries; let first = first; let idx = index" class="radio-inline" >
<input type="radio" [(ngModel)]="person.testBoolean" name="radiogroup" [checked]="first" [value]="entry.id" />{{ entry.description }}
</div>
like image 32
Duncan Faulkner Avatar answered Dec 29 '22 08:12

Duncan Faulkner