Last active
June 24, 2018 15:21
-
-
Save realtomaszkula/d243ecd64601e7a568219de0db056781 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface CarouselContext { | |
$implicit: string; | |
controller: { | |
next: () => void; | |
prev: () => void; | |
}; | |
} | |
@Directive({ | |
selector: '[carousel]' | |
}) | |
export class CarouselDirective implements OnInit, OnDestroy { | |
timerId: number | null = null; | |
context: CarouselContext | null = null; | |
index = 0; | |
constructor( | |
private tpl: TemplateRef<CarouselContext>, | |
private vcr: ViewContainerRef | |
) {} | |
@Input('carouselFrom') images: string[]; | |
private _autoplayDelay: number; | |
@Input('carouselWithDelay') | |
set autoplayDelay(autoplayDelay: number) { | |
this._autoplayDelay = autoplayDelay; | |
} | |
get autoplayDelay() { | |
return this._autoplayDelay || 1000; | |
} | |
@Input('carouselAutoplay') | |
set autoplay(autoplay: 'on' | 'off') { | |
autoplay === 'on' ? this.setAutoplayTimer() : this.clearAutoplayTimer(); | |
} | |
ngOnInit(): void { | |
this.context = { | |
$implicit: this.images[0], | |
controller: { | |
next: () => this.next(), | |
prev: () => this.prev() | |
} | |
}; | |
this.vcr.createEmbeddedView(this.tpl, this.context); | |
} | |
ngOnDestroy() { | |
this.clearAutoplayTimer(); | |
} | |
next() { | |
this.index++; | |
if (this.index >= this.images.length) { | |
this.index = 0; | |
} | |
this.context.$implicit = this.images[this.index]; | |
} | |
prev() { | |
this.index--; | |
if (this.index < 0) { | |
this.index = this.images.length - 1; | |
} | |
this.context.$implicit = this.images[this.index]; | |
} | |
private clearAutoplayTimer() { | |
window.clearInterval(this.timerId); | |
} | |
private setAutoplayTimer() { | |
this.timerId = window.setInterval(() => this.next(), this.autoplayDelay); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment