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 Dec 2023
Publisher Packt
ISBN-13 9781803233444
Length 536 pages
Edition 2nd 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 (16) Chapters Close

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

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

Can you imagine being able to instantly jump to any place that your eyes can see? That would be awesome! Wouldn’t it? But what if we wanted our app to be able to do that? In this recipe, you’ll create a directive that the user can click to jump to specific sessions in an Angular application.

Getting ready

The app that we are going to work with resides in start/apps/chapter02/ng-scroll-to-directive inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-scroll-to-directive
    

    This should open the app in a new browser tab, and you should see the following:

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

How to do it…

  1. First, 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 workspace root folder:
    cd start && nx g directive scroll-to --directory apps/chapter02/ng-scroll-to-directive/src/app/directives
    

    If asked, choose the @nx/angular:component schematics and choose the “As provided” action.

  1. Now, we need to make the directive capable of accepting an @Input() that’ll contain the CSS Query Selector for our target section, which 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 = '';
    }
    
  2. Now, we’ll apply the appScrollTo directive to the links in the app.component.html file along with the respective targets. We’ll replace the href attribute with the target attribute. The code should look like this:
    ...
    <main class="content" role="main">
      <div class="page-links">
        <h4 class="page-links__heading">
          Links
        </h4>
        <a class="page-links__link" appScrollTotarget=
          "#resources">Resources</a>
        <a class="page-links__link" appScrollTotarget=
          "#nextSteps">Next Steps</a>
        <a class="page-links__link" appScrollTotarget=
          "#moreContent">More Content</a>
        <a class="page-links__link" appScrollTotarget=
          "#furtherContent">Further Content</a>
        <a class="page-links__link" appScrollTotarget=
          "#moreToRead">More To Read</a>
      </div>
    </main>
      ...
    <a appScrollTo target="#toolbar" class="to-top-button w-12
      h-12 text-white flex items-center justify-center">
      <span class="material-symbols-outlined text-3xl text-
        white"> expand_less </span>
    </a>
    
  3. 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);
      }
      ...
    }
    
  4. We will now implement the logic to scroll to a particular target. 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 to the target element. With this change, you should see the page scrolling 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);
        if (!targetElement) {
           throw new Error('`target' is required.`);
        }
        targetElement.scrollIntoView();
      }
      ...
    }
    
  5. All right—we got the scroll to work. “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'});
      }
    }
    

How it works…

The essence of this recipe is the web API that we’re using within an Angular directive, which 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.

See also

You have been reading a chapter from
Angular Cookbook - Second Edition
Published in: Dec 2023
Publisher: Packt
ISBN-13: 9781803233444
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 $19.99/month. Cancel anytime