I'm trying to put data-driven radio buttons in a table. I've successfully been able to bind the buttons to the model. However, it behaves very oddly when I select a new option.
The underlying model works fine, I can see it by outputting the expected values in the table. However, when I click a radio button, all of the radio buttons in that column get selected.
I've seen others discussing issues with this, and everyone has recommended to use the index and refer to the array object. I've done this, but it's still behaving as described above.
Here's some quick sample code:
component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
users = [
{id: "amy", role: "admin"},
{id: "bob", role: "noob"},
{id: "glenn", role: "1337"},
{id: "stacy", role: "client"},
]
}
component.html
<table class="table">
<tr>
<th>Name</th>
<th>Email</th>
<th>Administrator</th>
<th>Inspector</th>
<th>Client</th>
</tr>
<tr *ngFor="let user of appData.users.users; let x = index;">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<div class="control">
<input type="radio" [name]="appData.users.users[x].id+'-role'" value="admin" [(ngModel)]="appData.users.users[x].role">
</div>
</td>
<td>
<div class="control">
<input type="radio" [name]="appData.users.users[x].id+'-role'" value="inspector" [(ngModel)]="appData.users.users[x].role">
</div>
</td>
<td>
<div class="control">
<input type="radio" [name]="appData.users.users[x].id+'-role'" value="client" [(ngModel)]="appData.users.users[x].role">
</div>
</td>
<td>{{x}}</td>
<td>{{appData.users.users[x].role}}</td>
</tr>
</table>
I've put together a quick stackblitz that shows the problem in action: https://stackblitz.com/edit/angular-tkptcn. Please help!
The names of a radio group have to match. the code below should work
<table>
<tr>
<th>user</th>
<th>role</th>
<th>admin</th>
<th>noob</th>
<th>1337</th>
<th>client</th>
</tr>
<tr *ngFor="let user of users; let x=index;">
<td>{{users[x].id}}</td>
<td>{{users[x].role}}</td>
<td><input type="radio" [name]="user" value="admin" [(ngModel)]="users[x].role"></td>
<td><input type="radio" [name]="user" value="noob" [(ngModel)]="users[x].role"></td>
<td><input type="radio" [name]="user" value="1337" [(ngModel)]="users[x].role"></td>
<td><input type="radio" [name]="user" value="client" [(ngModel)]="users[x].role"></td>
</tr>
</table>