Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Angular Cookbook

You're reading from   Angular Cookbook Over 80 actionable recipes every Angular developer should know

Arrow left icon
Product type Paperback
Published in Aug 2021
Publisher Packt
ISBN-13 9781838989439
Length 652 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Muhammad Ahsan Ayaz Muhammad Ahsan Ayaz
Author Profile Icon Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Winning Components Communication 2. Chapter 2: Understanding and Using Angular Directives FREE CHAPTER 3. Chapter 3: The Magic of Dependency Injection in Angular 4. Chapter 4: Understanding Angular Animations 5. Chapter 5: Angular and RxJS – Awesomeness Combined 6. Chapter 6: Reactive State Management with NgRx 7. Chapter 7: Understanding Angular Navigation and Routing 8. Chapter 8: Mastering Angular Forms 9. Chapter 9: Angular and the Angular CDK 10. Chapter 10: Writing Unit Tests in Angular with Jest 11. Chapter 11: E2E Tests in Angular with Cypress 12. Chapter 12: Performance Optimization in Angular 13. Chapter 13: Building PWAs with Angular 14. Other Books You May Enjoy

Creating a basic directive that allows you to vertically scroll to an element

In this recipe, you'll create a directive to allow the user to scroll to a particular element on the page, on click.

Getting ready

The project for this recipe resides in chapter02/start_here/ng-scroll-to-directive:

  1. Open the project in VS Code.
  2. Open the terminal, and run npm install to install the dependencies of the project.
  3. Once done, run ng serve -o.

    This should open the app in a new browser tab, and you should see something like this:

Figure 2.3 – ng-scroll-to-directive app running on http://localhost:4200

Figure 2.3 – ng-scroll-to-directive app running on http://localhost:4200

How to do it…

  1. First off, we'll create a scroll-to directive so that we can enhance our application with smooth scrolls to different sections. We'll do this using the following command in the project:
    ng g directive directives/scroll-to
  2. Now, we need to make the directive capable of accepting an @Input() that'll contain the Cascading Style Sheets (CSS) Query Selector for our target section that we'll scroll to upon the element's click event. Let's add the input as follows to our scroll-to.directive.ts file:
    import { Directive, Input } from '@angular/core';
    @Directive({
      selector: '[appScrollTo]'
    })
    export class ScrollToDirective {
      @Input() target = '';
      constructor() { }
    }
  3. Now, we'll apply the appScrollTo directive to the links in the app.component.html file along with the respective targets so that we can implement the scroll logic in the next steps. The code should look like this:
    ...
    <div class="content" role="main">
      <div class="page-links">
        <h4 class="page-links__heading">
          Links
        </h4>
        <a class="page-links__link" appScrollTo     target="#resources">Resources</a>
        <a class="page-links__link" appScrollTo     target="#nextSteps">Next Steps</a>
        <a class="page-links__link" appScrollTo     target="#moreContent">More Content</a>
        <a class="page-links__link" appScrollTo     target="#furtherContent">Further Content</a>
        <a class="page-links__link" appScrollTo     target="#moreToRead">More To Read</a>
      </div>
      ...
      <div class="to-top-button">
        <a appScrollTo target="#toolbar" class=    "material-icons">
          keyboard_arrow_up
        </a>
      </div>
    </div>
  4. Now, we'll implement the HostListener() decorator to bind the click event to the element the directive is attached to. We'll just log the target input when we click the links. Let's implement this, and then you can try clicking on the links to see the value of the target input on the console:
    import { Directive, Input, HostListener } from '@angular/core';
    @Directive({
      selector: '[appScrollTo]'
    })
    export class ScrollToDirective {
      @Input() target = '';
      @HostListener('click')
      onClick() {
        console.log(this.target);
      }
      ...
    }
  5. Since we have the click handler set up already, we can now implement the logic to scroll to a particular target. For that, we'll use the document.querySelector method, using the target variable's value to get the element, and then the Element.scrollIntoView() web API to scroll the target element. With this change, you should have the page being scrolled to the target element already when you click the corresponding link:
    ...
    export class ScrollToDirective {
      @Input() target = '';
      @HostListener('click')
      onClick() {
        const targetElement = document.querySelector     (this.target);
        targetElement.scrollIntoView();
      }
      ...
    }
  6. All right—we got the scroll working. "But what's new, Ahsan? Isn't this exactly what we were already doing with the href implementation before?" Well, you're right. But, we're going to make the scroll super smoooooth. We'll pass scrollIntoViewOptions as an argument to the scrollIntoView method with the {behavior: "smooth"} value to use an animation during the scroll. The code should look like this:
    ...
    export class ScrollToDirective {
      @Input() target = '';
      @HostListener('click')
      onClick() {
        const targetElement = document.querySelector     (this.target);
        targetElement.scrollIntoView({behavior: 'smooth'});
      }
      constructor() { }
    }

How it works…

The essence of this recipe is the web API that we're using within an Angular directive, and that is Element.scrollIntoView(). We first attach our appScrollTo directive to the elements that should trigger scrolling upon clicking them. We also specify which element to scroll to by using the target input for each directive attached. Then, we implement the click handler inside the directive with the scrollIntoView() method to scroll to a particular target, and to use a smooth animation while scrolling, we pass the {behavior: 'smooth'} object as an argument to the scrollIntoView() method.

There's more…

You have been reading a chapter from
Angular Cookbook
Published in: Aug 2021
Publisher: Packt
ISBN-13: 9781838989439
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime