I am trying to code a carousel/slider with Angular 2. Idea in my mind is, I have a array of images,
export class AppComponent {
title = 'app works!';
images: Array<any> = [
{
image: "1.jpg"
},
{
image: "2.jpg"
},
{
image: "3.jpg"
},
{
image: "4.jpg"
},
{
image: "5.jpg"
},
{
image: "6.jpg"
}
];
}
I want to loop through the image array and replace the background image of a div with the current value of {{images.image}}.
I have set up a counter,
public subscription: any;
public time: any;
ngOnInit() {
let timer = TimerObservable.create(1000,5000);
this.subscription = timer.subscribe(t=>{
this.time = t;
})
}
and the target div would look something like
<div class="slider__home" style="background: url({{image}})">
</div>
How do I achieve this? I don't want to use bootstrap or jQuery, but just plain Angular2, thanks for any help.
Like this:
<div class="slider__home" [style.background]="'url('+ image +')'">
</div>
You can use bootstrap carousel like this:
index.html
<html>
<head>
<!-- Insert all css data here -->
</head>
<body>
<carousel></carousel>
<!-- Insert all needed scripts here -->
<script>
System.import('carousel.js');
</script>
</body>
</html>
carousel.html
<div id="carousel-generic" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div *ngFor="let url of urls" class="item" [ngClass]="{active: isActive(url)}">
<img src="{{url}}" alt="{{url}}">
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
carousel.ts
// <reference path="jquery.d.ts" />
// <reference path="boodstrap.d.ts" />
import {Component} from '@angular/core';
import {Http} from '@angular/http';
@Component({
selector: "carousel",
templateUrl: 'carousel.html'
})
export class CarouselComponent {
private start = false;
urls = [];
constructor(http: Http) {
http.get('/getcarousel')
.subscribe(res => this.startCarousel(res.json()));
}
startCarousel(urls: string[]) {
this.urls = urls;
$('.carousel').carousel();
}
isActive(url: string) {
return url === this.urls[0];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With