In my application, I have a page where the user selects a focus item from a table (see simplified example below, circles represent radio buttons):
Select | Name | Qty | Description |
---|---|---|---|
○ | apple | 152 | crisp red fruit |
○ | banana | 253 | soft yellow fruit |
○ | cranberry | 124 | small red berry |
○ | etc. | etc. | etc. |
Each row is created like so from an item
table, each item having the properties item_id
, name
, qty
, and desc
:
<tr ngFor="let i of items">
<td><input id="selectedItem_{{i.item_id}}" type="radio" name="selecteditem" [(ngModel)]="selectedItem" [value]="i.item_id" (click)=selectItem(i.item_id) >
<td>{{i.name}}</td>
<td>{{i.qty}}</td>
<td>{{i.desc}}</td>
</tr>
The selectItem(i.item_id)
function updates a global variable global_selectedItem
to be i.item_id
, because the value is used on other pages within the app. That functionality works, but I would like it to be that if someone returns to this page, the radio button that corresponds to the currently selected item (i.e. when global_selectedItem == i.item_id
) shows up as "checked". How do I do this? I've tried the following possibilities, none of which have worked.
<input id="selectedItem_{{i.item_id}}" type="radio" name="selecteditem" [(ngModel)]="selectedItem" [value]="i.item_id" (click)=selectItem(i.item_id) checked="global_selectedItem==i.item_id">
<input id="selectedItem_{{i.item_id}}" type="radio" name="selecteditem" [(ngModel)]="selectedItem" [value]="i.item_id" (click)=selectItem(i.item_id) [checked]="global_selectedItem==i.item_id">
EDIT: I have made a stackblitz for the problem.
CodePudding user response:
You are very close.
2 fixes:
- remove the ngModel
- add brackets around checked attribute
So:
<input type="radio"
[name]="'selecteditem_' i.item_id"
[value]="i.item_id"
[checked]="i.item_id===selectedItem.item_id"
(click)="selectItem(i.item_id)">
Working stackblitz: https://stackblitz.com/edit/angular-ivy-mofmnb?file=src/app/app.component.html