Get Angular2/4 Carousel from service to loop over

2019-06-14 02:25发布

I have a carousel in Angular. It is relatively simple to embed slide images in the html, but I want to insert them from an array in a service.

My html looks like this:

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <ul class="carousel-item active">
      <li *ngFor="let image of visibleImages" >
        <img src="{{image.url}}" class ="tn">
      </li>
    </ul>

  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

My ts for the component looks like this:

import { Component, OnInit } from '@angular/core';
import { ImageServiceService } from '../image-service.service';

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.css']
})
export class ImageSliderComponent implements OnInit {
    visibleImages: any[] = [];

  constructor(private imageService: ImageServiceService) {
    this.visibleImages = this.imageService.getImages();
  }

  ngOnInit() {
  }

}

And my ts for the service looks like this:

import { Injectable } from '@angular/core';

@Injectable()
export class ImageServiceService {

    visibleImages = [];
    getImages(){
        return this.visibleImages = IMAGES.slice(0);
    }

    getImage(id: number){
            return IMAGES.slice(id).find(image => image.id === id);
    }

}

const IMAGES = [
    {"id": 1, "category": "paintings", "caption": "a painting", "url": '../assets/SBI_Slide_1.jpg'},
    {"id": 2, "category": "paintings", "caption": "a painting", "url": '../assets/Eagle_Slide_2.jpg'},
    {"id": 3, "category": "paintings", "caption": "a painting", "url": '../assets/Knot_Slide_3.jpg'},
];

First I want to loop over the images, instead of displaying them all at once. It might be good if there was a wait between stages of the loop?

Next I want to trigger going forward or backward through the loop with a method?

1条回答
祖国的老花朵
2楼-- · 2019-06-14 02:57

Try this package. It should work for what you want to accomplish.

Edit:

Your slideshow could look something more like this, which is more modular and cleaner:

<div *ngFor="let slide of slides" [class.hide-slide]="!slide.selected" class="text-center slides margin-bottom">
  <app-slide
    [imageUrl]="slide.url"
    [slideTitle]="slide.title"
    [bodyText]="slide.body"
 ></app-slide>
</div>

Check out this plunkr for an implementation I used based on W3 Schools CSS slideshow.

查看更多
登录 后发表回答