I got this problem in my angular app. I have many options in a mat-radio-group but these are dynamically placed according to a json object. Something like this:
This is the json object
{
"list": [
{"name": "some name 1", ID: "D1"},
{"name": "some name 2", ID: "D2"}
]
}
in this example there are just two objects in my list, but could be 9, 20 or any number of objects.
So I want that in my html is that no matter how many objects are, only the first one is selected, even if the list change just the first object stay selected.
This is my html:
<mat-radio-group name="opList" fxLayout="column">
<mat-radio-button *ngFor="let op of listOfOptions" name="opList" >{{ op.name}}</mat-radio-button>
</mat-radio-group>
the listOfOptions
variable have the JSON object.
How do I always set selected the first object?
Add a checked
property in the JSON
{
"list": [
{"name": "some name 1", ID: "D1", "checked": true},
{"name": "some name 2", ID: "D2", "checked": false}
]
}
and then
<mat-radio-group name="opList" fxLayout="column">
<mat-radio-button *ngFor="let op of listOfOptions"
[checked]="op.checked" name="opList" >{{ op.name}}</mat-radio-button>
</mat-radio-group>
Use [value]="op.name"
and make a binding to your Component variable like [(ngModel)]="chosenItem"
HTML:
<mat-radio-group name="opList" fxLayout="column" [(ngModel)]="chosenItem">
<mat-radio-button *ngFor="let op of list" [value]="op.name" name="opList" >{{ op.name}}</mat-radio-button>
</mat-radio-group>
In your Component:
list = [
{ "name": "some name 1", ID: "D1"},
{ "name": "some name 2", ID: "D2"}
]
chosenItem = this.list[0].name;
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