Sharing Top Content from the Angular-sphere.

Building a Simple Carousel Component with Angular – Netanel Basal

  • In this article, we will create a simple carousel component with Angular that includes animation with the help of the Animation Builder service.
  • We need a wrapper element with overflow: hidden and a fixed width we will define later as equal to the width of a carousel item.
  • Later, we will use the Animation Builder service to animate the transform property of the carousel element.
  • Note: You can also use ViewChild to get the first element, but I wanted to illustrate this method in case you want to build a carousel with dynamic width.
  • The carousel property is a reference to the native DOM element of the carousel.

In this article, we will create a simple carousel component with Angular that includes animation with the help of the Animation Builder service. We will also discuss several approaches to querying…

In this article, we will create a simple carousel component with Angular that includes animation with the help of the Animation Builder service. We will also discuss several approaches to querying the DOM.

The following will be our final result:

Let’s start by creating the carousel component.

The Component CSSHere, we’ll use a well-known CSS technique. We need a wrapper element with overflow: hidden and a fixed width we will define later as equal to the width of a carousel item. We must also set the carousel element to display: flex so the items appear in the same row. Later, we will use the Animation Builder service to animate the transform property of the carousel element.

Let’s continue to see how we can pull the items out of the template.

Building the Carousel Item DirectiveThe Carousel Item directive is a structural directive. We can leverage Dependency Injection to get a reference to the template.

Rendering The ItemsNow, let’s see how we can use this data in the parent component.

We can query for the CarouselItemDirective instances in our template with the ContentChildren decorator. Then we loop through them, passing the CarouselItemDirective.tpl property that holds a reference to a template to the ngTemplateOutlet directive. ( which we can get from the CarouselItemDirective constructor via DI ).

Setting The Wrapper WidthAs I mentioned before, we need to set the wrapper element width to the same as the first…

Building a Simple Carousel Component with Angular – Netanel Basal