我正在尝试为投资组合构建一些有意义的动作。目标是当用户点击作业项目时,该项目会弹出并增长。为此,我相信我必须更改数组中单击元素的状态,但是当我现在单击它时,它会影响数组内所有元素的所有状态。谁能解释我发生了什么以及如何解决?
portfolio.component.ts
import { Component } from '@angular/core';
import { trigger,style,transition,animate,keyframes,state,query,stagger } from '@angular/animations';
export class Job {
id: number;
title: string;
}
const JOBS: Job[] = [
{ id: 11, title: 'Item 1' },
{ id: 12, title: 'Item 2' },
{ id: 13, title: 'Item 3' },
];
@Component({
selector: 'portfolio',
templateUrl: './portfolio.component.html',
styleUrls: ['./portfolio.component.css'],
animations: [
trigger('enlarge', [
state('small', style({
height: '100px',
})),
state('large', style({
height: '200px',
background: 'red',
})),
transition('small <=> large',
animate('1s ease-in')),
]),
]
})
export class PortfolioComponent {
title = 'Portfolio';
jobs = JOBS;
state: string = 'small'
enlarge() {
this.state = (this.state === 'small' ? 'large' : 'small');
}
}
portfolio.component.html
<div class="list"
*ngFor='let job of jobs'
[@enlarge]='state'
(click)="enlarge()">
<div for="#">{{job.id}} - {{job.title}}</div>
</div>
答案 0 :(得分:3)
通过一些外部帮助和研究,我找到了解决问题的方法。
<强> portfolio.component.ts 强>
import { Component } from '@angular/core';
import { trigger,style,transition,animate,keyframes,state,query,stagger } from '@angular/animations';
export class Job {
id: number;
title: string;
state: string;
}
@Component({
selector: 'portfolio',
templateUrl: './portfolio.component.html',
styleUrls: ['./portfolio.component.css'],
animations: [
trigger('enlarge', [
state('small', style({
height: '100px',
transform: 'translateY(0)',
})),
state('large', style({
height: '200px',
transform: 'translateY(-300px)',
background: 'red'
})),
]),
]
})
export class PortfolioComponent {
title = 'Portfolio';
jobs = [
{ id: 11, title: 'Item 1', state: 'small' },
{ id: 12, title: 'Item 2', state: 'small' },
{ id: 13, title: 'Item 3', state: 'small' },
];
enlarge(index) {
index.state = (index.state === 'small' ? 'large' : 'small');
}
}
<强> portfolio.component.html 强>
<div class="list"
*ngFor='let job of jobs'
[@enlarge]='job.state'
(click)="enlarge(job)">
<div for="#">{{job.id}} - {{job.title}}</div>
</div>
答案 1 :(得分:1)
目前,您使用相同的变量为所有项目分配相同的状态。您需要做的是为每个项目分配不同的状态。
为所有项目设置默认状态:
this.jobs = this.jobs.map((job) => {
job.state = "small";
return job;
});
更新模板:
将[@enlarge]='state'
设为[@enlarge]='job.state'
更新enlarge()
方法:
enlarge(index) {
let job = this.jobs[index].state;
job = (job === 'small' ? 'large' : 'small');
}