Image carousel in Angular 6

PGH picture PGH · Dec 27, 2018 · Viewed 13.7k times · Source

I need an image carousel for my application (Angular v6), while surfing I found this solution i,e using ngx-drag-scroll. Is there any other way to do the image carousel like this ?

Scroll

Without using jquery/javascript,using only Typescript - can I achieve this?

Any help full resources. I want a carousel to display the card component inside it.

Answer

Tom picture Tom · Jan 2, 2019

angular material card slider

Is there any other way to do the image carousel like this ?

Yes

Without using jquery/javascript,using only Typescript - can I achieve this?

Yes (well TypeScript is a super set of JavaScript and you still need to interact with the DOM but yeah)


Here is a StackBlitz demo of a simple implementation that seems to behave, look and feel like your requirements. (For example you can pass it Material Card components).

It basically works like this: you give the SliderComponent DOM Elements (SliderItemDirectives) and it will add the current most left Element's width to the scroll position of the slider container when you click right. Clicking left subtracts width. I have made use of ContentChildren and ViewChild to get to the widths and scrollLeft property. The animation is achieved with the css scroll-behavior: smooth;.

Here is the main Component:

import { Component, AfterContentInit, ContentChildren, ViewChild, QueryList, ElementRef } from '@angular/core';
import { SliderItemDirective } from './slider-item.directive';

@Component({
  selector: 'app-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.scss']
})
export class SliderComponent implements AfterContentInit {

  @ContentChildren(SliderItemDirective, { read: ElementRef }) items
    : QueryList<ElementRef<HTMLDivElement>>;
  @ViewChild('slides') slidesContainer: ElementRef<HTMLDivElement>;

  private slidesIndex = 0;

  get currentItem(): ElementRef<HTMLDivElement> {
    return this.items.find((item, index) => index === this.slidesIndex);
  }

  ngAfterContentInit() {
    console.log('items', this.items);
  }

  ngAfterViewInit() {
    console.log('slides', this.slidesContainer);
  }

  onClickLeft() {
    this.slidesContainer.nativeElement.scrollLeft -= this.currentItem.nativeElement.offsetWidth;

    if (this.slidesIndex > 0) {
      this.slidesIndex--;
    } 
  }

  onClickRight() {
    this.slidesContainer.nativeElement.scrollLeft += this.currentItem.nativeElement.offsetWidth;

    if (this.slidesIndex < this.items.length - 1) {
      this.slidesIndex++
    }
  }
}