Tutorial

Responsive Carousel Component with Angular 2

Draft updated on Invalid Date
Default avatar

By Chris Nwamba

Responsive Carousel Component with Angular 2

This tutorial is out of date and no longer maintained.

Note: Updates:

  • March 22, 2016: Provided a Demo Link which is available on Plunker
  • March 21, 2016: Updated a poorly formatted markdown. A { instead of a [ for a link.

Introduction

The web is growing. It is growing so fast that if you don’t catch up you might not be able to shine bright in your career as a web developer.

A few months ago I started hearing about Web Components from the mouths of so-called professional developers. I knew it was one of those new things that “I don’t really need now, but I must learn it for the future”. Unfortunately, for poor me, Angular, which has always been my favorite JavaScript framework, decided to componentize everything.

What are Web Components?

This concept is one of the standards of the web that can boast of being easy to grasp.

Basically, web components give room for you to simply bundle these tags with their styles and scripts as a reusable component that is exposed via one tag (instead of littering your HTML with similar confusing tags).

A component is basically just a grouping of HTML/JS/CSS all in one.

Where Does Angular 2 Come In?

Web Components are a new standard that will be here to stay because it is widely accepted. The problem is that we web devs know how this new stuff rolls.

Web Components is widely accepted, but not widely supported on browsers, and this is where Angular 2 comes in.

Angular 2 is the “new guy”. It implements components at its core and makes it simple to work with components in our daily web projects.

I understand that the reason why a lot of us have yet to embrace this “new guy” is because learning Angular 1 was not fun and now we are hearing of another version with a different concept. The good news is Angular 2 is actually simple and you just need 4-5 days to start doing wonders with it.

Now enough talking. Let’s have a little fun making a CSS-based (and I really mean CSS-based) carousel component with Angular 2.

Setting Up Angular 2

npm has become so popular that, recently, tutorials forget to remind us to install them. Therefore, kindly install Node so as to get its package manager, npm.

Create a folder in your favorite directory. This will be located probably in your projects folder or desktop. Name it angular2-carousel-component. Navigate via your CLI to this created folder.

Create package.json and tsconfing.json at the root of the folder with the following contents:

package.json:

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.1",
    "typescript": "^1.7.3"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

The tsconfig.json file is a configuration file for TypeScript (more on that later) which the properties are explained here in the “Appendix: TypeScript configuration” section. We can go ahead and install the dependencies by running:

  1. npm install

Add two more folders, app and images. Our main application codes will be in the app folder, but you can copy the images for the slides here into the images folder.

We are all set to make our component, but before we do that, let us explain the CSS-based carousel and how it is implemented.

Carousels are one of the most popular concepts in the web, but it has its own price. There are heavy images to display and scripts to manipulate the image slides.

How about we just endure only the pain caused by these images and leave out the troubles of JavaScript? How about we make a Carousel with just CSS? How possible is that?

Actually making Carousels has never been easy until I read Harry Roberts article on his blog. Before you get so excited about this simplicity, be sure that your Carousel will be dead simple and basic, and won’t have many controls. Just be rest assured that it will be a RESPONSIVE “carousel”.

Assuming we have a template as shown below:

<div class="carousel">

  <ul class="slides">

    <li>
      <h2>We are covered</h2>
      <img src="images/covered.jpg" alt="">
    </li>

    <li>
      <h2>Generation Gap</h2>
      <img src="images/generation.jpg" alt="">
    </li>

    <li>
      <h2>Potter Me
      <img src="images/potter.jpg" alt="">
    </li>

    <li>
      <h2>Pre-School Kids</h2>
      <img src="images/preschool.jpg" alt="">
    </li>

    <li>
      <h2>Young Peter Cech</h2>
      <img src="images/soccer.jpg" alt="">
    </li>

  </ul>

</div>

Harry’s idea is to make the .slides wrapper have a width that is equal to the number of slides multiplied by the viewport. So, assuming our viewport is 100% and we have 5 items, the width of the slides should be 500% so as to contain all the slides when aligned horizontally.

We may leave the CSS implementation for now and see it while making the carousel component.

Tying Everything Together

Angular 2 uses Typescript, which from a general perspective is a semi-language that compiles to JavaScript. It implements everything JS, but just gives that feel of strictness that C-based languages have that JS does not have. Don’t be overwhelmed, it is just a “cool JavaScript”.

Microsoft has a TypeScript plugin for Sublime which will help you with hinting, syntax highlighting, and many other those goodies

There are also many other TypeScript plugins for various editors which makes using TypeScript easy no matter what environment you work in.

As the idea is to make strict applications, let us first define an interface for the images collection. The interface is just like in any other language, it is a signature that we must adhere to if we care to use it. In the app folder, add a file named image.interface.ts:

export interface Image {
  title: string;
  url: string;
}

You do not have to understand what interfaces are before you can follow this tutorial.

We just exported an Image Interface that will serve as a signature for the collection of our images. This is typically saying that if you want to make an image collection that implements that interface, it must have a title and url property of type string.

Now that we have a signature, we can go ahead and create the carousel component. Create carousel.component.ts in the app directory:

// Import Component form the angular core package
import {Component} from 'angular2/core';

// Import the Image interface
import {Image} from './image.interface';

// Compoent Decorator
@Component({
  //Name of our tag
  selector: 'css-carousel',
  //Template for the tag
  template: `
 <div class="carousel">

  <ul class="slides">

    <li *ngFor="#image of images">
      <h2>{{image.title}}</h2>
      <img src="{{image.url}}" alt="">
    </li>

  </ul>

</div>
  `,
  //Styles for the tag
  styles: [`
.carousel{
    overflow:hidden;
    width:100%;
}
.slides{
    list-style:none;
    position:relative;
    width:500%; /* Number of panes * 100% */
    overflow:hidden; /* Clear floats */
        /* Slide effect Animations*/
    -moz-animation:carousel 30s infinite;
    -webkit-animation:carousel 30s infinite;
    animation:carousel 30s infinite;
}
.slides > li{
    position:relative;
    float:left;
    width: 20%; /* 100 / number of panes */
}
.carousel img{
    display:block;
    width:100%;
    max-width:100%;
}
.carousel h2{
    margin-bottom: 0;
    font-size:1em;
    padding:1.5em 0.5em 1.5em 0.5em;
    position:absolute;
    right:0px;
    bottom:0px;
    left:0px;
    text-align:center;
    color:#fff;
    background-color:rgba(0,0,0,0.75);
    text-transform: uppercase;
}

@keyframes carousel{
    0%    { left:-5%; }
    11%   { left:-5%; }
    12.5% { left:-105%; }
    23.5% { left:-105%; }
    25%   { left:-205%; }
    36%   { left:-205%; }
    37.5% { left:-305%; }
    48.5% { left:-305%; }
    50%   { left:-405%; }
    61%   { left:-405%; }
    62.5% { left:-305%; }
    73.5% { left:-305%; }
    75%   { left:-205%; }
    86%   { left:-205%; }
    87.5% { left:-105%; }
    98.5% { left:-105%; }
    100%  { left:-5%; }
}
  `],
})
//Carousel Component itself
export class CSSCarouselComponent {
    //images data to be bound to the template
  public images = IMAGES;
}

//IMAGES array implementing Image interface
var IMAGES: Image[] = [
  { "title": "We are covered", "url": "images/covered.jpg" },
  { "title": "Generation Gap", "url": "images/generation.jpg" },
  { "title": "Potter Me", "url": "images/potter.jpg" },
  { "title": "Pre-School Kids", "url": "images/preschool.jpg" },
  { "title": "Young Peter Cech", "url": "images/soccer.jpg" }
];

When we ran the npm install command, we pulled the Angular 2 package into our folder. The first line is importing the Angular core library. We also imported the Image interface that we created earlier as we will make use of it here. Notice that we do not have to add the .ts extension when importing.

The file is exporting a CSSCarouselComponent class which has a public property of an array of images implementing image interface. The class also has a @Component decorator which is specifying the meta-properties of this class. The selector is the name we want the tag to have and the template is the HTML for the component and styles, which is the CSS trick we played to get our carousel working.

Note: Angular 2 supports 3 types of styles which are template-inline, component-inline, and external CSS. Just like the normal way, you can add styles directly to template tags which are referred to as template-inline. This is unlike old times, an acceptable practice, because of encapsulation.

Component-inline is what we just implemented in our demo above while external can be achieved by just replacing the component-inline styles with: [styleUrls: 'style.css']

Next up is to create our app component which just serves as a parent. The app component is like the building in the illustration I made while introducing this article. It has the same skeleton as the carousel component. Create app.component.ts in app folder with the following contents:

//import Component from angular core
import {Component} from 'angular2/core';

//import our Carousel Component
import {CSSCarouselComponent} from './carousel.component';

//@Component decorator
@Component({
  //tag
  selector: 'my-app',
  //template
  template: `
  <div class="wrapper">
    <css-carousel></css-carousel>
    </div>
  `,
   //css
  styles: [`
   .wrapper{
      width: 60%;
      margin: 60px auto;
    }
  `],
  //tell angular we are using the css-carousel tag in this component
   directives: [CSSCarouselComponent]
})
//actual class
export class AppComponent { }

The major difference here is the directives property in the @Component decorator which is an array of all the imported components that we will use on this component. Notice we already imported the CSSCarouselComponent after importing angular’s core library.

We can now boot up the app. All there is to do when booting is to import angular, import the app to boot, and boot with the bootstrap() method. Create a file in app with the name boot.ts:

//Import Angular core
import {bootstrap}    from 'angular2/platform/browser'
//Import App Component
import {AppComponent} from './app.component'
//Boot
bootstrap(AppComponent);

As usual, an index.html entry point is needed for our cool app. Create one on the root and update it with:

<!-- head -->
    <title>CSS Carousel Angular 2 Compopnent</title>

    <!-- 1. Load libraries -->
    <!-- #docregion libraries -->
    <!-- #docregion ie-polyfills -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <!-- #enddocregion ie-polyfills -->

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <!-- #enddocregion libraries -->

    <!-- 2. Configure SystemJS -->
    <!-- #docregion systemjs -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>
    <!-- #enddocregion systemjs -->
<!-- body -->
    <my-app>Loading...</my-app>

Some JavaScript libraries are included, but you should care more about System.js which is a third-party library that adds ES6 module loading functionality across browsers. As seen in the file it helps load our bootstrap file app/boot in the index.html file.

You can run the app via your CLI with:

  1. npm start

Conclusion

Web components are going to trend whether we are ready for it or not. Even if we are to keep trends aside, web components are really an appreciated and accepted concept. Some tools like Polymer and React already started a good job, but if you love angular like me, then Angular 2 is an awesome option.

One last thing, forget the competition among these tools, just stick to what you can afford because they all meet the basic requirements you need to make a web component application.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Chris Nwamba

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel