当我单击/选择时,我想对单选按钮列表中选择的项目进行某些更改(背景颜色,文本颜色,突出显示等)。该列表来自ngFor项循环,我认为这就是为什么什么都不起作用的原因。我现在所拥有的确实在单击时将颜色从红色更改为蓝色,但是它更改了列表中的所有项目,而不是所选的单个项目。
我尝试在CSS中使用li :: selection,但这没用。
<div class="container">
<div class="col-sm-12 form-group">
<p> <strong> Select Your Subject</strong></p>
<ng-container *ngFor="let subs of allSubjects">
<ul id="subList">
<li [ngClass]="{'blue' : toggle, 'red': !toggle}">
<label>
<input checked type="radio" name="ClassTimesSubjects"
[(ngModel)]="subs.classTimeSubjectsName"
[value]="subs.classTimeSubjectsName"
[(ngModel)]="ClassTimesSubjects" #ClassSubjects="ngModel" required
(click)="enableDisableRule()">
{{ subs.classTimeSubjectsName }}
<img [src]="subs.classTimeSubjectsImage" id="subPics">
</label>
</li>
</ul>
</ng-container>
</div>
</div>
打字稿...
toggle = true;
status = "Enable";
public allSubjects: Array<any>;
enableDisableRule(job) {
this.toggle = !this.toggle;
this.status = this.toggle ? "Enable" : "Disable";
}
CSS ...
.blue {
background-color: blue;
}
.red {
background-color: red;
}
答案 0 :(得分:2)
您应该使用这样的东西
<ul>
<li *ngFor="let item of data" [ngClass]="{'blue' : selectedValue==item.id, 'red': selectedValue!=item.id}" >
<input type="radio" name="group" [(ngModel)]="selectedValue" [value]="item.id"/> {{item.name}}</li>
</ul>
打字稿
selectedValue=1
data = [
{ id: 1, name: 'A', selected: false },
{ id: 2, name: 'B', selected: true },
{ id: 3, name: 'C', selected: false }]
}
答案 1 :(得分:1)
要获得预期结果,请对ngFor中的每个元素使用索引切换
代码示例-https://codesandbox.io/s/angular-2be5t
app.component.js
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
toggle = [];
status = "Enable";
allSubjects = [
{
classTimeSubjectsName: "test1",
classTimeSubjectsImage: ""
},
{
classTimeSubjectsName: "test12",
classTimeSubjectsImage: ""
}
];
enableDisableRule(i) {
let idx = 0;
while (idx < this.allSubjects.length) {
this.toggle[idx] = false;
idx++;
}
this.toggle[i] = !this.toggle[i];
this.status = this.toggle[i] ? "Enable" : "Disable";
}
}
<div class="container">
<div class="col-sm-12 form-group">
<p><strong> Select Your Subject</strong></p>
<ng-container *ngFor="let subs of allSubjects; let i =index">
<ul id="subList">
<li [ngClass]="{'blue' : toggle[i], 'red': !toggle[i]}">
<label>
<input
checked
type="radio"
name="ClassTimesSubjects"
[(ngModel)]="subs.classTimeSubjectsName"
[value]="subs.classTimeSubjectsName"
[(ngModel)]="ClassTimesSubjects"
#ClassSubjects="ngModel"
required
(click)="enableDisableRule(i)"
/>
{{ subs.classTimeSubjectsName }}
<img [src]="subs.classTimeSubjectsImage" id="subPics" />
</label>
</li>
</ul>
</ng-container>
</div>
</div>
答案 2 :(得分:1)
尝试使用ngModel /数据绑定。您可以按照以下代码进行操作。
<ul>
<li [ngClass]="{'blue' : checked, 'red': !checked}">
<input type="checkbox" [(ngModel)]="checked" />
</li>
</ul>