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;
};
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With