Angular 13: How to make a clickoutside Directive with RXjs

Going outside with clickoutside directives

Hi all, it has certainly been a while, even though the only comments I get are from bizarre spam bots. As always there is a TLDR for you down below. So lets get into it.

Have you ever been in a situation where you make a lovely custom dropdown menu for someone and you do not know how to close the dropdown when you or they click away?

Well this is where a directive comes in and we even get to use fancy Rxjs in the mix.

Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior.

First off you will need to create your directive would recommend using the Angular CLI tool on this one.

// Angular generate new service
ng g s servicename

[Pro tip]: If you are unsure where the CLI tool will place your directive you can use the extension –dry-run.

We will be using RXjs in this directive to listen to the clicking of the element outside the assigned element

TLDR here is the Directive code to handle the clicking outside directive. Be sure to declare the Directive in your module that you are using said directive.

import { DOCUMENT } from "@angular/common";
import { AfterViewInit, Directive, ElementRef, EventEmitter, Inject, OnDestroy, Output } from "@angular/core";
import { filter, fromEvent, Subscription } from "rxjs";

@Directive({
    selector: '[appClickOutside]',
})

export class ClickOutsideDirective implements AfterViewInit, OnDestroy {
    @Output() appClickOutside = new EventEmitter<void>();

    documentClickSubscription: Subscription | undefined;

    constructor(
        private element: ElementRef,
        @Inject(DOCUMENT) private document: Document,
    ) { }

    ngAfterViewInit(): void {
        // you are listening for a click anywhere on the document
        this.documentClickSubscription = fromEvent(this.document, 'click')
            .pipe(
                filter((event) => {
                    // the Rxjs filter will return when a click is not within the directive element
                    return !this.isInside(event.target as HTMLElement);
                }),
            )
            .subscribe(() => {
                // upon the case of element clicked outside the subscription will be emitted
                this.appClickOutside.emit();
            });
    }

    ngOnDestroy(): void {
        this.documentClickSubscription?.unsubscribe();
    }

    isInside(elementToCheck: HTMLElement): boolean {
        return (
            elementToCheck === this.element.nativeElement ||
            this.element.nativeElement.contains(elementToCheck)
        );
    }
}

How does this directive work?

The finer detail is that the subscription is being used to subscribe to specifically where the user is clicking on the document. The pipe contains a filter which checks if the user has clicked off the element or on the element, this is where we subscribe to said subscription to when the event has been clicked outside the element. The emitter will emit the appClickOutside emitter.

I don’t care how it works, what else must I do to get this setup in my project!

Assuring that you have created your directive and have declared it in your module next you will need to update the view. On the view of your component you will need to add the appClickOutside directive to the element that wraps around your custom dropdown menu, as you can see on line 2 I have a dropdown wrapper class to ensure that I have the area of the dropdown covered so you may need to specify the height or width depending on your layout.

If the click off is not quite working, I’d advice to take look at your styles and element wrapper.

Ya that is about it. Feel free to take a look at my working sample on github if you are facing any challenges

Angular how to make reuseable components with @Output Part 2

If you have read my first post covering @inputs then be sure to give that a quick read before continuing.

In the previous post we have covered all our inputs and you might be thinking what about @outputs, well lets make one. When you have an @output it would emit a value up to the parent component, I believe there are many ways to do this, but all I’m trying to say is that @output requires at least an emmitter. As seen in the card.profle component. (picture below).


Update the following code in the app.component.ts file:
  data = [
    {
      name: 'Jonny Doe',
      job: 'FrontEnd Gopher',
      bio: 'I am a Gopher that likes to FrontEnd Gophe',
    },
    {
      name: 'John Dear',
      job: 'Dear FrontEnd',
      bio: 'I am a Dear that likes to dearly FrontEnd',
    },
    {
      name: 'Tony Tones',
      job: 'FrontEnd Developer',
      bio: 'I am a Tony Tones,I use JavaScript, TypeScript and Angular Framework',
    },
  ];

  ngOnInit() {
    this.userProfiles = this.data;
  }

Refresh and you should have 3 loverly gophers staring at you.

In this example we will link the follow button to emit the username of the profile selected to the parent component. This exercise we will use the eventmitter to help us emit the profile name selected to the parent component.

Line 13 we have our @output named btnClick connected to our new eventEmitter of type string (for our name variable).

We use the buttonClicked() function and pass the variable name in the buttonClick(name), which we have declared in our cardprofile component and the next step is to link it on the app.component.html and you can see the emitter btnClick.

And finally to add the function in the app component

Now spin up the project and open the dev tools and click on one of the profiles.

Here we are console logging the profile username to the parent component and thats about it.


Feel free to fork my github, here is the source code.

Generate new Angular project in specific directory

*solution I came across is at the bottom of the post. If you want to read about my experience then just keep on reading*.

I normally come across this issue when i haven’t created a new angular project in a while. Making the directory of such project before building the project using the Angular CLI. So you have made a file called ‘this-is-where-my-project-will-live’. When you say

ng new MYAMAZINGNEWAPPTHATIVEALWAYSWANTEDTOMAKE 

You will find that a new file has been generated and it’ll be looking something like this or you would need to drill down further into your file to get to the project itself.

So you think to yourself well, i might as well just cut and paste the entire project and….well forget that, here is an easier way.

To set where you want your project to be build use this little code snippet.

SOLUTION:

ng new MYAMAZINGNEWAPPTHATIVEALWAYSWANTEDTOMAKE --directory ./this-is-where-my-project-will-live

This will build your solution exactly into the specified directory, here is the sauce. The project will still have the same name, but will be located in folder that you have specified in the cmd.

hope that this helps you guys out

Angular: Unit Testing with Services and how to mock ’em

Ok, if you don’t know anything about Services this post is not for you JUST yet. Learn about em and come back here…if you wanna.

For those that made it past my first two lines and continued, we all know that services handle API calls and make real requests. Testing code that requires a service would normally need to receive or send data. You do not want to make real calls, you want to run this unit of code in isolation with no external dependencies. Unit tests normally run with CI (continuous Integration). It is just not feasible to make real API calls (with the chance of failing or taking long time for responses and potential failures). So the question that you want answered is, How to mock API service calls for unit tests?

I have recently come across this problem seeing that I am an official FrontEnd developer (this has happened basically 4 weeks ago still fresh) and one of my duties is to create unit tests for my work. I did some basic assertions which worked fine but there came a problem when it came to requiring a service to unit test my code.

Let’s provide some context. You have a service called EventsService right, this guy has a method/call called getUsers. Simple. Now in the component that you are working with you need to import the EventsService to use that getUsers call for your unit tests as well as import the component you are unit testing.

So you use this guy(above) that makes the getUsers() method that is provided from the eventService upon the component’s ngOnInit() as seen in the image (still above).

With the code above this will make the request and return an observable which you can see we are subscribing to and initialising. So let us get to our spec component.

Added some comments for each step, sorry i know that there is a bit going on in this post. I tell ya explaining context is quite a challenge.

So you have declared and imported what services you need, and from there use spyOn to return an observable and set the data you wish to return, after that you would trigger the ngOnInit() from your component. There you have it, you have successfully faked an API call to return data that is to your liking and forming it at your will

Ideally the flow with unit testing is to use the 3 A rule

  • Arrange
  • Act
  • Assert

in the example i’ve been going on about, you can see that the first step was to arrange that service to provide mock data, the act would be to trigger the ngOnInit() from my users component and then Assert to see if the expect results are true.

Of course i am a newbie at this and i’ve i’m completely wrong please feel free to comment and point me in the right direction. Of course there are many way to peel a banana.

the Above examples is using Karma + Jasmine and Angular framework.

Angular Toast Notifications, quick! (for newbies)

Alright alright, it has been a long time. Now it’s time to take you through how to add a toast notification and fast.

The quickest and easiest way I could find was using this lil npm package from ngx-toastr is what you need for a quick and simple implementation.

Following the guide and going through the steps its pretty straight forward, but if you are having any troubles like i have…on that one time, i’m happy to share my findings.

Step one:

npm install ngx-toastr --save
// and if you already have it installed
npm install @angular/animations --save

Cool so let that little console run. Once installed be sure to add the imports to your app module like so

Add them imports to your app.module.ts

As you can see I have added something a little extra to the ToastrModule.forRoot({}), in those brackets you can do a number of tricks, adjust positioning animation and the works here are some details

and there are a number of options more

Now you need to add the stylings so the app knows how to make your toastie look good, check out your styles.css the main one ya’ll know what i’m talking about. You have a number of styling imports. This is where you need to be a tiny bit careful and note what style libraries you are using is it Bootstrap? Angular material? is it something else? Luckily we can do an import for whatever your style framework that you have implemented.

// regular style toast 
@import '~ngx-toastr/toastr';
 
// bootstrap style toast 
// or import a bootstrap 4 alert styled design (SASS ONLY) 
// should be after your bootstrap imports, it uses bs4 variables, mixins, functions 
@import '~ngx-toastr/toastr-bs4-alert';
 
// if you'd like to use it without importing all of bootstrap it requires 
@import '~bootstrap/scss/functions';
@import '~bootstrap/scss/variables';
@import '~bootstrap/scss/mixins';
@import '~ngx-toastr/toastr-bs4-alert';

So the problem i was facing was that i have implemented the toast notifications and all but they were not displaying. Turns out i was not using the correct toastr import styles. So lil lesson for me be sure to take note on what styling framework/libraries you are using. I used the regular toast implementation.

For my implementation of the toast notifications i wanted to add it as a service/shared component so it can be reused throughout the app..well “web-app” I am making, it looks a lil something like this (toast-message.service.ts).

import { Injectable } from '@angular/core';
import { ToastrService } from "ngx-toastr";

@Injectable({
  providedIn: 'root'
})
export class ToastMessageService {
  constructor(private toastr: ToastrService) { }
    showSuccess(text: string, title: string) {
        this.toastr.success(text, title);
    }
    showFail(text: string, title: string) {
      this.toastr.error(text, title);
  }
}

this way i’m able to inject this service into the constructor and utilise my toastie notifications for both success and error scenarios also having the freedom of adding my own text for the success/failure situation.


import { ToastMessageService } from "../../services/toast-message.service";
export class SomeCoolComponent implements OnInit {
  constructor(private toastr: ToastMessageService) {}

ngOnInit() {
this.toastr.showSuccess(
           // Body content of toastie
           "Has been successfully created.",
           // Header of toastie
            "A Toast notification"
          );
this.toastr.showError(
           // Body content of toastie
           "Has been successfully created an error.",
           // Header of toastie
            "A Toast notification for the masses and friends"
          );
}
}

I think that that about does it. This should be quick and simple, my project is running Angular 7. Lemme know if you come across any issues.

Angular Http deprecated??!!

I know that this post is a little click batey, but I was in a total shock when I heard the news and you won’t believe what happened next.

Angular developers are outraged, I think

You may be asking when did this happen ( 20 Aug 2017 apparently) and what am i supposed to do now, I’ve got this tutorial that I’m following but this geyser is using Http!

Don’t stress, Angular is now using an improved method to handle HTTP requests using HttpClient. I’m going to go over some basics.

Firstly you will need to add HttpClient to your app.model.ts file in the imports section. You may be asking do I have to, my reply is if you want this to work yes.

Cool, so with that done we have access to all the HttpClientModule’s tricks.
I have created a service component to show off my http skills, be sure to import the httpClient as …HttpClient on top of your typeScript file like so.

So you’ve happily imported your HttpClient, and created your constructor with (http: HttpClient). Now you’re seeing a compile error and thinking…

what is dees?!

If you add a “private” in the constructor you will see that the http will be available throughout that specific ts file and the compile error will magically disappear , so do not stress.

You may not have tried using a service components, this is just to clean up your code and put it into good reading order. Best practice for api calls to be located into these service component files. As you can see in the screenshot below that i reference the service call to get access to the api calls for my application.

i.e. be sure to not share end points to the public, but this end point is for practice and funzies so knock yourself out with jsonplaceholder.typicode.com

For more information about httpClient be sure to checkout Angular docs.

How to fix 404 not found error failed to load favicon.ico

I was hunting around the net for a solution to this little bugger. The solution i found is quite a simple one. If there is a better way, be sure to let me know in the comments. Here is a step by step on how to fix this issue.

Note the file structure and the index.html within the src folder

You want to open up your index.html within your src folder and in your <Header /> tag and add the following:

<link rel="shortcut icon" href="../src/assets/img/favicon.ico">

It should look a little something like this your index.html

using the link tag, this should render your favicon

I believe that it is best practice to use an ICO formatted icon for cross browser functionality. If using a png, you can use just about any online ico converter.

Unit testing with Enzyme and Jest and How to

You had a taste of what its like to set your React project up with unit testing and now you want some more?

Where to start, I think for this particular post I’ll demonstrate how to do some simple assertions and check conditions to be true. If you want to have a more in-depth go, just give a clicky here.

I know that each project is different and unit tests check for a number of things, I was told that there are essentially three steps, define your variables, add your conditions and check whether they are true. Before we tackle the above steps, we’ll need to add some data-tags in our js so that we know how to locate each element for sure (instead of using css/xpath or jquery).

You know what elements to unit test against, be sure to add data tags, should look something like this.

i’ve added some qa data tags

Cool, so we have our data tags all set, now its time to add our *.test.js file, be sure to name it nicely so everyone can know what component this test script is testing.

Now you have a nice new blank [COMPONENT_NAME].test.js file, first step is to be sure to import what you need to make this unit test run for the hills

gotta add your imports (these guys should be available after setting up for unit testing

import React from 'react';
import { shallow } from 'enzyme';

you will also need to import the component that you are unit testing against, so in my case it’ll be the following

import Weather from './Weather';

Now in my weather component i do have a few variables that get populated by an API, so in this case i’ll be mocking them values and giving them a default value due to these values can change depending on the API responses.

const C_TEMP = 'C_TEMP';
const LOCATION = 'LOCATION';
const WEATHERNAME = 'WEATHERNICENAME';

You guys are still with me right? just hold on so now we are going to actually write our first unit test…. in fact i think that this was my first unit test that i’ve ever wrote, hence why its not quite perfect.

the syntax is more or less the same structure when creating a unit test with Jest, you will add a short description on what the unit test is actually testing, kinda like below, i’ll add some comments in below to break it down exactly what it is I’m doing:

1 test('should render a `location to exist`', () => {
2    const wrapper = shallow(<Weather
3        location={LOCATION}
4        cTemp={C_TEMP}
5        WEATHERNAME={WEATHERNAME}
6    />);
7    const expected = true;
8    const actual = wrapper.find('.location').exists();
9    expect(actual).toBe(expected);
10 });

line 1: Adding a description for my unit test, so i’m essentially checking if the element exists.
line 2 to 6: Declaring a const using Enzyme’s shallow function to render the element on its own without worrying about the parent/child structure, so i’m rendering on the weather component with the variables i’m expecting
line 7: I declare a const as my expected conditions, so i want this existence to be true
line 8: Now to state what is actually happening, so i’m saying in the wrapper i expect location className to exists.
line 9: Lastly, here i’m simply stating that actual results to equals to expected
line 10. Closing the unit test

Excellent, in your package.json you should have the ‘test’ script with the following config 

"scripts: {
"test": "jest --config=./jest.config.json --coverage",
},

if you have made a couple of assertions and unit tests, when executing npm test this should run all your unit tests, and you’ll get a pretty graph at the end of it and it should look something like this

So i have added some additional unit tests as you can see by the results table, one of my unit tests actually render my first unit test (does this element exists) redundant, cause if it didn’t exists my other unit tests would not pass…so sometimes things like that happen when you have to keep things dry (don’t repeat yourself). Let me know if you were able to get your first unit test running.

This blog post took me a bit of time to write, so if you are facing any problems please let me know and i’ll see if I can assist. I’m not saying that i’m the best and i know everything , but this is what worked for me.

thanks again for reading, catch you next time.