在Angular的*ngFor指令中,无法直接获取先前的元素。然而,你可以使用索引来获得先前的元素。
以下是一种解决方法:
下面是一个示例代码:
在组件中:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Current Item: {{ item }}
Previous Item: {{ getPreviousItem(i) }}
`
})
export class ExampleComponent {
items = [1, 2, 3, 4, 5];
previousItem: number;
getPreviousItem(index: number): number {
if (index === 0) {
return null;
}
return this.items[index - 1];
}
}
在上面的示例中,我们使用了一个名为previousItem
的变量来存储先前的元素。getPreviousItem()
方法根据索引返回先前的元素。在模板中,我们使用getPreviousItem()
方法来显示先前的元素。
请注意,对于第一个元素,我们返回null作为先前的元素。你可以根据你的需求调整这个逻辑。
希望这个解决方法对你有帮助!