how to execute next after few seconds for a carousel in angular?

Issue

I am using ng2-carouselamos for a carousel to display with below code successfully.

<div
    ng2-carouselamos
    class="slides-wrapper"
    [items]="items"
    [width]="1200"
    [$prev]="prev"
    [$next]="next"
    [$item]="item">
  </div>

  <ng-template #prev>
    <img src="assets/images/left_arrow.png" id="left" />
  </ng-template>
  <ng-template #next>
    <img src="assets/images/right_arrow.png" id="right" />
  </ng-template>
  <ng-template #item let-item let-i="index">
    <div class="items">
      <img src="{{ item.name }}">
    </div>
  </ng-template> 

and ts as below:

this.items = [
      { name: 'assets/images/professional_website.jpg' },
      { name: 'assets/images/nature_1200_800.jpg' },
      { name: 'assets/images/nature.jpg' },
      { name: 'assets/images/nature.jpg' },
      { name: 'assets/images/nature.jpg' }, ]

how to call [$next]=”next” from within ts to automatically executes it after 5 sec?

Thanks.

Solution

The source of your problem is to call a function (the next call) every 5 seconds.

So as noted in answer:

You can use setInterval(), the arguments are the same.

setInterval(function() {
  // method to be executed;
}, 5000);

And thus, in your case, on ngInit you can have this type of code:

// we need to access programmatically the scroll function since it isn't exposed 
// by the library
@ViewChild(Ng2Carouselamos)
ng2Carouselamos : Ng2Carouselamos;

setInterval(function() {
  ng2Carouselamos.scroll(true,items);
}, 5000);

However, since the library you are using isn’t maintained any more and lacks simple features (such as autoscroll) I’d suggest opting for a more modern component library (like prime-ng which supports this with continuous=true ) or Ngu-Carousel

Answered By – Giannis Smirnios

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.