Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Angular Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Angular Cookbook

Angular Cookbook

By : Muhammad Ahsan Ayaz
4 (13)
close
close
Angular Cookbook

Angular Cookbook

4 (13)
By: Muhammad Ahsan Ayaz

Overview of this book

Angular has long been the framework of choice for web development projects of various scales, offering much-needed stability and a rich tooling ecosystem for building production-ready web and mobile apps. This recipe-based guide ensures high performance apps with the latest version of Angular, helping you to build up your Angular expertise with a wide range of recipes across key tasks in web development. In this second edition, the recipes have been updated, added, and improved based on developer feedback, new challenges, and Angular 17. The first few chapters will show you how to utilize core Angular concepts such as components, directives, and services to get you ready for building frontend web apps. You’ll then develop web components with Angular and go on to learn about advanced concepts such as dynamic components loading and state management with NgRx for achieving real-time performance. Later chapters will focus on recipes for effectively testing your Angular apps to make them fail-safe, before progressing to techniques for optimizing your app’s performance. Finally, you’ll create Progressive Web Apps (PWA) with Angular to provide an intuitive experience for users. By the end of this book, you’ll be able to create full-fledged, professional-looking Angular apps and have the skills you need for frontend development.
Table of Contents (16 chapters)
close
close
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

bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY