Owl carousel with Angular 6 (Banner Slider and Image Carousel)
Yes! You read it correctly.
I know it is very easy, but someone like me may find it difficult because I lost a few of my good hours behind it.
I am going with the assumption that you already have an Angular 6 setup. If not, then you can download the code for this story from here or go for a fresh installation from here(recommended, & please follow instructions till Step 3).
Step 1: Go to the project folder. Most Important step, hehe :)
Step 2: We have to install a few packages, use
npm install ngx-owl-carousel owl.carousel jquery --savengx-owl-carousel: It will help to use feature rich Owl Carousel of jQuery to get integrated with Angular easily. It could be seen as a wrapper on the Owl Carousel mainly written in jQuery.
owl.carousel: It is the main package, where the magic happens. You need this for the .css files and the .js file of this package.
jQuery: Yes! you need it, even in Angular. It is required for main Owl Carousel to work.
Step 3: In project’s root folder, look for angular.json file. Add the below lines to the "styles" and "scripts" (add to the first ones in the angular.jsonfile) This step is to add the required .css and .js files to the application of Angular.
"styles": [
"src/styles.css",
"./node_modules/owl.carousel/dist/assets/owl.carousel.min.css",
"./node_modules/owl.carousel/dist/assets/owl.theme.default.min.css"],"scripts": [
[
"./node_modules/jquery/dist/jquery.min.js",
"./node_modules/owl.carousel/dist/owl.carousel.min.js"
]
Step 3: Go to app.module.ts and add the below lines
import { OwlModule } from 'ngx-owl-carousel';// Add OwlModule to imports tooimports: [
BrowserModule,
OwlModule
]
Step 4: Go to app.component.ts and below lines insideexport class AppComponent{}to generate an array with image urls to make the carousel or slider. If the items is 1, then you will get a banner slider as it will render only one image in the whole section at any moment. However, if items is set to 3 (this is default), then you will have an image carousel with images width properly divided according to the parent div.
mySlideImages = [1,2,3].map((i)=> `https://picsum.photos/640/480?image=${i}`);myCarouselImages =[1,2,3,4,5,6].map((i)=>`https://picsum.photos/640/480?image=${i}`);mySlideOptions={items: 1, dots: true, nav: false};
myCarouselOptions={items: 3, dots: true, nav: true};
Step 5: Go to app.component.html and below lines to the html part of the code
<owl-carousel [options]="mySlideOptions" [items]="images" [carouselClasses]="['owl-theme', 'sliding']" >
<div class="item" *ngFor="let image of mySlideImages;let i = index">
<div>
<img src={{image}}/>
</div>
</div>
</owl-carousel>Note: You may have to add extra css for proper structure.
Please clone my git repo from here to have a demo.
For any queries, first check the below links (you should try, I am too). Even if not resolved, please let me know. I will try my best!!!