我正在尝试将angular animation
应用于个人list item
。在鼠标悬停时,它会获得一些颜色,并且在鼠标移动时颜色会发生变化。
使用ngFor
生成列表。
问题是当我hoverover
一个li item
时,所有li items
都会突出显示。
// list component ts
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css'],
animations: [
trigger('usrSt', [
state('active', style({ 'background-color': '#cfd8dc' })),
state('inactive', style({ 'bacckground-color': '#fff' }))
])
]
})
export class ListComponent implements OnInit, OnDestroy {
public personsList;
st = 'active';
@Input() coursestat: string;
constructor(private getDt: InputDataService) {
}
ngOnInit() {
this.personsList = this.getDt.personArr;
console.log(this.personsList);
}
ngOnDestroy() {
console.log('destroy list');
}
onMouseover() {
this.st = 'active';
}
onMouseleave() {
this.st = 'inactive';
}
}
// list component html
<li class="list-group-item" (mouseover)="onMouseover()" (mouseleave)="onMouseleave()" [@usrSt]="st" [routerLink]= "['/users', i+1, person.name]" *ngFor="let person of (personsList | filter:coursestat:'chosenCourse'); let i = index">
答案 0 :(得分:0)
因为您使用ngFor循环每个li并使用相同的 st
解决方案:
为li编写一个单独的组件并为其使用动画。
实施例
list.component.html
<app-my-li *ngFor="let person of (personsList | filter:coursestat:'chosenCourse'); let i = index"></app-my-li>
APP-MY-li.component.ts
@Component({
selector: 'app-my-li',
templateUrl: './app-my-li.component.html',
styleUrls: ['./app-my-li.component.css'],
animations: [
trigger('usrSt', [
state('active', style({ 'background-color': '#cfd8dc' })),
state('inactive', style({ 'bacckground-color': '#fff' }))
])
]
})
export class ListComponent implements OnInit, OnDestroy {
// you might wanna input user person data here
st = 'active';
constructor() { }
ngOnInit() {
}
ngOnDestroy() {
}
onMouseover() {
this.st = 'active';
}
onMouseleave() {
this.st = 'inactive';
}
}
APP-MY-li.component.html
<li (mouseover)="onMouseover()" (mouseleave)="onMouseleave()" [@usrSt]="st"></li>
没有新组件
export class ListComponent implements OnInit, OnDestroy {
public personsList;
sts = new Array<string>();
@Input() coursestat: string;
constructor(private getDt: InputDataService) {
}
ngOnInit() {
this.personsList = this.getDt.personArr;
// this.sts = Array.from(this.personalList, _ => 'active');
this.personalList.forEach(_ => this.sts.push('active'));
console.log(this.personsList);
}
ngOnDestroy() {
console.log('destroy list');
}
onMouseover(i: number) {
this.sts[i] = 'active';
}
onMouseleave(i: number) {
this.sts[i] = 'inactive';
}
}
<li class="list-group-item" (mouseover)="onMouseover(i)" (mouseleave)="onMouseleave(i)" [@usrSt]="sts[i]" [routerLink]= "['/users', i+1, person.name]" *ngFor="let person of (personsList | filter:coursestat:'chosenCourse'); let i = index">