Book Image

Angular Cookbook

By : Muhammad Ahsan Ayaz
Book Image

Angular Cookbook

By: Muhammad Ahsan Ayaz

Overview of this book

The Angular framework, powered by Google, is the framework of choice for many web development projects built across varying scales. It’s known to provide much-needed stability and a rich tooling ecosystem for building production-ready web and mobile apps. This recipe-based guide enables you to learn Angular concepts in depth using a step-by-step approach. You’ll explore a wide range of recipes across key tasks in web development that will help you build high-performance apps. The book starts by taking you through core Angular concepts such as Angular components, directives, and services to get you ready for building frontend web apps. You’ll develop web components with Angular and go on to cover 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 Angular book, you’ll be able to create full-fledged, professional-looking Angular apps and have the skills you need for frontend development, which are crucial for an enterprise Angular developer.
Table of Contents (15 chapters)

Enhancing template type checking for your custom directives

In this recipe, you'll learn how to improve type checking in templates for your custom Angular directives using the static template guards that the recent versions of Angular have introduced. We'll enhance the template type checking for our appHighlight directive so that it only accepts a narrowed set of inputs.

Getting ready

The project we are going to work with resides in chapter02/start_here/enhanced-template-type-checking, inside the cloned repository:

  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.8 – enhanced-template-type-checking app running on http://localhost:4200

Figure 2.8 – enhanced-template-type-checking app running on http://localhost:4200

Now that we have the app running, let's see the steps for this recipe in the next section.

How to do it…

  1. First off, we'll try to identify the problem, and that boils down to the ability to pass any string as a color to the highlightColor attribute/input for the appHighlight directive. Give it a try. Provide the '#dcdcdc' value as the input and you'll have a broken highlight color, but no errors whatsoever:
    ...
    <div class="content" role="main">
      ...
      <p class="text-content" appHighlight   [highlightColor]="'#dcdcdc'"   [highlightText]="searchText">
        ...
      </p>
    </div>
  2. Well, how do we fix it? By adding some angularCompileOptions to our tsconfig.json file. We'll do this by adding a flag named strictInputTypes as true. Stop the app server, modify the code as follows, and rerun the ng serve command to see the changes:
    {
      "compileOnSave": false,
      "compilerOptions": {
        ...
      },
      "angularCompilerOptions": {
        "strictInputTypes": true
      }
    }

    You should see something like this:

    Figure 2.9 – strictInputTypes helping with build time errors for incompatible type

    Figure 2.9 – strictInputTypes helping with build time errors for incompatible type

  3. Well, great! Angular now identifies that the provided '#dcdcdc' value is not assignable to the HighlightColor type. But what happens if someone tries to provide null as the value? Would it still be fine? The answer is no. We would still have a broken experience, but no error whatsoever. To fix this, we'll enable two flags for our angularCompilerOptionsstrictNullChecks and strictNullInputTypes:
    {
      "compileOnSave": false,
      "compilerOptions": {
        ...
      },
      "angularCompilerOptions": {
        "strictInputTypes": true,
        "strictNullChecks": true,
        "strictNullInputTypes": true
      }
    }
  4. Update the app.component.html file to provide null as the value for the [highlightColor] attribute, as follows:
    ...
    <div class="content" role="main">
      ...
      <p class="text-content" appHighlight   [highlightColor]="null" [highlightText]="searchText">
       ...
    </div>
  5. Stop the server, save the file, and rerun ng serve, and you'll see that we now have another error, as shown here:
    Figure 2.10 – Error reporting with strictNullInputTypes and strictNullChecks in action

    Figure 2.10 – Error reporting with strictNullInputTypes and strictNullChecks in action

  6. Now, instead of so many flags for even further cases, we can actually just put two flags that do all the magic for us and cover most of our applications—the strictNullChecks flag and the strictTemplates flag:
    {
      "compileOnSave": false,
      "compilerOptions": {
       ...
      },
      "angularCompilerOptions": {
        "strictNullChecks": true,
        "strictTemplates": true
      }
    }
  7. Finally, we can import the HighlightColor enum into our app.component.ts file. We will add a hColor property to the AppComponent class and will assign it a value from the HighlightColor enum, as follows:
    import { Component } from '@angular/core';
    import { HighlightColor } from './directives/highlight.directive';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      searchText = '';
      hColor: HighlightColor = HighlightColor.LightCoral;
    }
  8. We'll now use the hColor property in the app.component.html file to pass it to the appHighlight directive. This should fix all the issues and make light coral the assigned highlight color for our directive:
    <div class="content" role="main">
    ...
      <p class="text-content" appHighlight   [highlightColor]="hColor" [highlightText]="searchText">
        ...
      </p>
    </div>

See also