要实现Angular中的ngFor Bootstrap轮播项只激活一次,可以使用ng-template结合ngIf指令来实现。
以下是一个示例代码:
HTML模板:
{{item.title}}
{{item.description}}
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-carousel',
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.css']
})
export class CarouselComponent {
items = [
{ title: 'Item 1', description: 'Description 1' },
{ title: 'Item 2', description: 'Description 2' },
{ title: 'Item 3', description: 'Description 3' }
];
activeIndex = 0;
isActive(index: number): boolean {
return index === this.activeIndex;
}
}
在上述示例中,使用了ngFor指令来迭代items数组,然后使用ng-template和ngbSlide指令来定义每个轮播项。在ng-template内部,使用ngIf指令来判断当前轮播项是否应该被激活。
通过在组件中定义一个activeIndex变量来跟踪当前激活的轮播项索引。然后,在isActive方法中,检查当前索引是否等于activeIndex。如果相等,则返回true,表示该轮播项应该被激活。
这样,只有与activeIndex匹配的轮播项将被激活,其他轮播项将被隐藏。