问题
I have a dynamic carousel and I'm pulling images directly from a node backend. Everything is working fine except my carousel is displaying all images at once instead of in a sliding motion because only the first slider needs to be active.
<div class="carousel-inner">
<div *ngFor="let data of gallery; let i=index" class="item active">
<img src="{{ data }}" alt="{{ name }}">
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
</div>
How do I make only the first dynamic slider to have the active class in the carousel?
回答1:
There are many ways to do this, one simple way is to tie the class assignment to which index you wish to be active. Perhaps something like this:
<div class="carousel-inner">
<div *ngFor="let data of gallery; let i=index" [class]="(i === activeIndex) ? 'active' : 'inactive'">
<img src="{{ data }}" alt="{{ name }}">
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
</div>
Where activeIndex is a component variable you choose which is the index of the data item you want active.
Or for a more detailed selection process tie it to a javascript function:
<div class="carousel-inner">
<div *ngFor="let data of gallery; let i=index" [class]="setClass(data, i)">
<img src="{{ data }}" alt="{{ name }}">
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
</div>
And now in your component:
setClass(data: DataType, i: number) {
let class: string = 'inactive';
/* more complex choice logic to set class = 'active' */
return class;
}
回答2:
There are many way to perform dynamic carousel below code will help you to fatch data dynamically.
<div class="carousel-inner">
<div class="carousel-item " [ngClass]="{active:isFirst}" *ngFor="let caroiselProduct of caroiselProducts;
index as i;first as isFirst">
<img src="{{caroiselProduct.img_src}}" alt="Los Angeles" width="1100px" height="400px">
<div class="carousel-caption">
<h3>{{caroiselProduct.product_name}}</h3>
<p>{{caroiselProduct.productsortdisc}}</p>
</div>
</div>
</div>
component.ts file
export class CarouselslideComponent implements OnInit {
constructor() { }
caroiselProducts=[
{
"img_src":"../../assets/demo1.jpg",
"product_name":"Demo1",
"productsortdisc": "this is caroisel discription"
},
{
"img_src":"../../assets/demo1.jpg",
"product_name":"Demo2",
"productsortdisc": "this is caroisel discription"
},
{
"img_src":"../../assets/demo1.jpg",
"product_name":"Demo3",
"productsortdisc": "this is caroisel discription"
}
];
ngOnInit() {
}
}
来源:https://stackoverflow.com/questions/53027047/angular-dynamic-carousel-active-class