Angular 角度4-在*ngFor中切换背景色
我是一个角度4的初学者。 我需要帮助用ngStyle设置样式。 我需要在单击一个Angular 角度4-在*ngFor中切换背景色,angular,Angular,我是一个角度4的初学者。 我需要帮助用ngStyle设置样式。 我需要在单击一个时设置样式,就像我将颜色更改为所有一样,我只需要在单击时更改颜色 模板: <div class="div1" id="sp1" align="center" > <ul class="r "> <li [ngStyle]="verde" *ngFor="let posto of posti" class="s ye" id="{{posto.id}}" title="" v
时设置样式,就像我将颜色更改为所有一样,我只需要在单击时更改颜色
模板:
<div class="div1" id="sp1" align="center" >
<ul class="r ">
<li [ngStyle]="verde" *ngFor="let posto of posti" class="s ye" id="{{posto.id}}" title="" value="{{posto.id}}" (click)="myclick($event)" >
{{posto.id}}
</li>
</ul>
</div>
要切换列表中的项目样式,请执行以下操作
在hello.component.ts中
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `
<div class="div1" id="sp1" align="center" >
<ul class="r ">
<li [class.background]="posto.isSelected" *ngFor="let posto of posti; let i=index" class="s ye" id="{{posto.id}}" title="" value="{{posto.id}}" (click)="myclick(posto)" >
{{posto.id}}
</li>
</ul>
</div>
`,
styleUrls: ["./hello.component.css"]
})
export class HelloComponent {
posti = [{id:1, isSelected:false}, {id:2, isSelected:false}];
constructor() {
}
selectedIndex:number = -1;
myclick(posto:any) {
posto.isSelected = !posto.isSelected;
}
}
.background{ background-color:green}
例如,您可以尝试以下操作
<div class="div1" id="sp1" align="center" >
<ul class="r " *ngFor="let posto of posti">
<li [ngStyle]="selectedId === posto.id" class="s ye" id="{{posto.id}}" title="" value="{{posto.id}}" (click)="myclick(posto)" >
{{posto.id}}
</li>
</ul>
</div>
可能的重复不是,这是同一场比赛,但我需要帮助解决另一个问题我不知道你以前是如何处理css的。你能用这些信息编辑你的帖子吗?您只需将规则.background{background color:green}
包含到现有css文件中即可。我尝试在css文件中包含.background{background color:green},但不更改颜色。对我来说很合适。你试过了吗?谢谢,为了保留所选的文章?当我点击另一个项目时,第一个项目仍然是彩色的,我不明白。您希望颜色保持不变还是只将颜色附加到单击的项目?在函数this.selectedId not exist中,selectedId是TS中的局部变量
<div class="div1" id="sp1" align="center" >
<ul class="r " *ngFor="let posto of posti">
<li [ngStyle]="selectedId === posto.id" class="s ye" id="{{posto.id}}" title="" value="{{posto.id}}" (click)="myclick(posto)" >
{{posto.id}}
</li>
</ul>
</div>
public selectedId : number;
myclick(posto){
this.selectedId = posto.id;
}