在Angular中,可以使用ngStyle指令来更改*ngFor循环中选定数组的背景颜色。下面是一个示例代码:
在组件中定义一个数组和一个变量来存储选定项的索引:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
{{ item }}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
selected: number;
selectItem(index: number) {
this.selected = index;
}
}
在模板中使用*ngFor循环迭代数组,并通过ngStyle绑定selected变量来更改背景颜色。当点击“Select”按钮时,调用selectItem方法来更新selected变量的值。
在上面的示例中,选定项的背景颜色将更改为黄色,其他项的背景颜色将保持为白色。你可以根据需要更改背景颜色的值。