所以,假设我有这个ngFor循环:
<ng-container*ngFor="let rate of [1,2,3,4,5]">
<div (click)="change()">{{myVariable}}</div>
</ng-container>
我在模板中有变量5显示的时间,我想要做的是在点击它之后更改变量,点击之前和之前的变量都会被更改,然后下一个保持不变。当我有:
export class StarRatingComponent {
myVariable = 'a';
change() {
this.myVariable = "b";
}
}
如果我点击a
然后所有都改为b
。如何仅对点击的项目和之前的项目应用此更改?所以对于例如。从aaaaa
到bbbaa
?
只需传递所选评级的值即可。
像这样的东西可以工作:
<ng-container*ngFor="let rate of [1,2,3,4,5]">
<div (click)="change(myVariable)">{{myVariable}}</div>
</ng-container>
然后在组件中,按索引跟踪它们:
export class RatingCmp {
rating: string = '1';
change(rating) {
this.rating = rating;
}
}
尝试使用以下方法:
<ng-container*ngFor="let value of values; index as i">
<div (click)="change(i)">{{value}}</div>
</ng-container>
export class StarRatingComponent {
values = this.generateValues('a',5);
private generateValues(val: string, times: number): string[]{
const result: string[] = [];
while(--times >= 0){
result.push(val);
}
return result;
}
change(index: number) {
while(index >= 0){
this.values[index] = 'b';
index--;
}
}
}