Macess  Hulk

Macess Hulk

1567237350

Exploring Life Cycle Hooks in Angular

There’s going to be nothing quite like this available on the web, as we will be promoting best practices, revealing hidden tips and tricks, and getting a real grasp on how and when these hooks are called.


Before we dive into the first installment of the series, let’s review briefly all of the available lifecycle hooks and where they can be used.

Available Lifecycle Hooks:

  • OnChanges
  • OnInit
  • DoCheck
  • AfterContentInit
  • AfterContentChecked
  • AfterViewInit
  • AfterViewChecked
  • OnDestroy

Lifecycle Hooks Can Be Used On:

  • Components
  • Directives

Here is a component with all eight (8) hooks implemented:

import {
  AfterContentChecked,
  AfterContentInit,
  AfterViewChecked,
  AfterViewInit,
  Component,
  DoCheck,
  OnChanges,
  OnDestroy,
  OnInit
} from '@angular/core';

@Component({
selector: ‘app-home’,
templateUrl: ‘./home.component.html’
})
export class HomeComponent
implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
ngOnChanges() {}

ngOnInit() {}

ngDoCheck() {}

ngAfterContentInit() {}

ngAfterContentChecked() {}

ngAfterViewInit() {}

ngAfterViewChecked() {}

ngOnDestroy() {}
}

If you’re like me, you had a few questions after reading the docs. Clean up what? Avoid memory leaks? Hey—that’s not very specific, it sounds like we need to uncover this a bit more. So here we go!

In this article, we will review how to implement OnDestroy, common use cases for OnDestroy, and wrap-up with a bonus enhancement to OnDestroy that will allow it to be executed with browser events.

A Brief Overview

OnDestroy is an Angular lifecycle method, that can hooked into on components and directives in Angular. By defining a specific method named ngOnDestroy on our class, we are telling the Angular runtime, that it should call our method at the appropriate time. This is a powerful and declarative way to add specific cleanup logic to the end of our class lifecycle.

Implementing OnDestroy

As with other Angular lifecycle methods, adding the actual hook for OnDestroy is relatively simple.

Add OnDestroy after the implements keyword

The first step to implementing OnDestroy is to add OnDestroy after the implements keyword on a component or directive.

Here’s a typical component without any lifecycle hooks:

import { Component } from ‘@angular/core’;

@Component({…})
export class MyValueComponent {}

Our first change is to import OnDestroy from Angular’s core and then create a contract with implements OnDestroy:

Fun Fact Time: Technically it’s not required to implement the interface, Angular will call ngOnDestroy regardless, however, it’s very helpful for type-checking, and to allow other developers to quickly identify which lifecycle hooks are in use on this class.
import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {}

Add the ngOnDestroy method to our class

Now that we have added the OnDestroy after implements the TypeScript intellisense will underline the class declaration in red, giving a warning that ngOnDestroy was not found. Let’s fix that by creating our new ngOnDestroy method.

Example Component Before:

import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {}

Example Component After:

import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {
ngOnDestroy() {
// cleanup logic goes here
}
}

You’ll also note that this lifecycle hook takes no arguments, unlike some of the others we’ll be covering in later articles.

Common Use Cases

As you can see, implementing OnDestroy is fairly straightforward. Now, let’s explore some common use cases for OnDestroy. At the beginning of the article, we mentioned that Angular recommends the following: “Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.” Let’s explore this further.

Avoiding Memory Leaks with OnDestroy

We want to avoid memory leaks, but what are they? According to Google’s definition, a memory leak is “a failure in a program to release discarded memory, causing impaired performance or failure.” Memory leaks are typically created from not understanding how things work and wreak havoc on app performance. Let’s explore an example of one such memory leak – so you’re primed to tackle your OnDestroy logic in future!

A Leaky ShowUserComponent

Let’s imagine a scenario wherein we have a component that has one button. When we click the button a call is made to a method on a AuthService that returns an Observable containing the name of the logged in user. The button click event subscribes to this Observable and displays a window alert with the username.

Here’s how the component might look before implementing OnDestroy:

show-user.component.ts

import { Component } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent {
constructor(private authService: AuthService) {}

showLoggedInUser() {
this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}
}

show-user.component.html

<button (click)=“showLoggedInUser()”>Show Logged In User</button>

At first glance, you might say, “This component looks great, it subscribes to the service and shows an alert on click”. You’d be correct, but what do you think would happen if this ShowUserComponent was used in the AppComponent and displayed with an *ngIf conditionally. Perhaps a scenario exists where the ShowUserComponent is destroyed and then displayed again.

Well, I can tell you what would happen, some really odd, strange behavior. If the component was instantiated, the user clicked the button and alert displayed, then one subscription would be created. Then let’s say, the component was re-created and the user clicked the button again, how times would the alert display? Two times, at least! This is because a second subscription would be created and then fired when the button is clicked.

This is creating the “memory leak” and could quickly get out of hand, with our alert being shown exponentially (just imagine the impact across an entire codebase without cleaning things up properly!). Let’s read on to learn how to plug this memory leak using OnDestroy.

Fixing the Leak on ShowUserComponent

To fix the memory leak we need to augment the component class with an implementation of OnDestroy and unsubscribe from the subscription. Let’s update our component adding the following:

  • Add OnDestroy to the typescript import
  • Add OnDestroy to the implements list
  • Create a class field named myUserSub: Subscription to track our subscription
  • Set this.myUserSub equal to the value of this.authService.getLoggedInUserName().subscription
  • Create a new class method named ngOnDestroy
  • Call this.myUserSub.unsubscribe() within ngOnDestroy if a subscription has been set.
Best Practice: Notice that we are checking if this.myUserSub is “truthy” before attempting to call unsubscribe. This avoids a potential situation wherein the subscription may have never been created, thus preventing a ghastly unsubscribe is not a function error message.

The updated component will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { Subscription } from ‘rxjs’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
}
}

Now we can ensure that our alert will only ever be displayed once per button click.

Great! Now we have some background on ngOnDestroy and how cleaning up memory leaks is the primary use case for this lifecycle method.

Additional Cleanup Logic

Exploring further, we find more examples of use cases for ngOnDestroyincluding making server-side cleanup calls, and preventing user navigation away from our component. Let’s explore these additional scenarios, and how we can enhance ngOnDestroy to meet our needs.

Making NgOnDestroy Async

As with other lifecycle methods in Angular, we can modify ngOnDestroywith async. This will allow us to make calls to methods returning a Promise. This can be a powerful way to manage cleanup activities in our application. As we read on we will explore an example of this.

Adding logic to call AuthService.logout from ngOnDestroy

Let’s pretend that we need to perform a server-side user logout when ShowUserComponent is destroyed. To do so we would update the method as follows:

  • Add async in front of the method name ngOnDestroy
  • Make a call to an AuthService to logout using the await keyword.

Our updated ShowUserComponent will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}

Tada! Now when the component is destroyed an async call will be made to logout the user and destroy their session on the server.

Unsubscribe versus takeUntil

As an alternative to manually calling unsubscribe you could take things a step further and make use of the takeUntil RxJS operator to “short-circuit” the subscription when a value is emitted.

Confused? Well imagine this…

  • Add a new private property to your component named destroyed$. This property will be a ReplaySubject<boolean> = new ReplaySubject(1), meaning it only ever emits one boolean value.
  • Add a .pipe to the this.authService.getLoggedInUserName()subscription
  • Pass takeUntil(this.destroyed$) into the pipe method
  • Update the ngOnDestroy method to push a new value to the destroyed$ subject, using this.destroyed$.next(true)
  • Update the ngOnDestroy method to call complete on the destroyed$ subject.

The finished component will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { ReplaySubject } from ‘rxjs’;
import { takeUntil } from ‘rxjs/operators’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.pipe(takeUntil(this.destroyed$))
.subscribe(username => window.alert(You are logged in as ${username}!));
}

async ngOnDestroy() {
this.destroyed$.next(true);
this.destroyed$.complete();
await this.authService.logout();
}
}

With this new method in place, we no longer need to keep track of each subscription, check for truthy and call unsubscribe. The real power of this comes into play, when we have multiple subscriptions that need to be unsubscribed from. At that point, we would just add the takeUntil to each subscription, and then leave our updated ngOnDestroy to emit the destroyed$ true value to all the subscriptions.

Advanced ngOnDestroy, Browser Events

Ensure Execution During Browser Events

Many developers are surprised to learn that ngOnDestroy is only fired when the class which it has been implemented on is destroyed within the context of a running browser session.

In other words, ngOnDestroy is not reliably called in the following scenarios:

  • Page Refresh
  • Tab Close
  • Browser Close
  • Navigation Away From Page

This could be a deal-breaker when thinking about the prior example of logging the user out on destroy. Why? Well, most users would simply close the browser session or navigate to another site. So how do we make sure to capture or hook into that activity if ngOnDestroy doesn’t work in those scenarios?

Decorating ngOnDestroy with HostListener

TypeScript decorators are used throughout Angular applications. More information can be found here in the official TypeScript docs.

To ensure that our ngOnDestroy is executed in the above mentioned browser events, we can add one simple line of code to the top of ngOnDestroy. Let’s continue with our previous example of ShowUserComponent and decorate ngOnDestroy:

  • Add HostListener to the imports
  • Place @HostListener(‘window:beforeunload’) on top of ngOnDestroy

Our updated ShowUserComponent will look something like this:

import { Component, OnDestroy, HostListener } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

@HostListener(‘window:beforeunload’)
async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}

Now our ngOnDestroy method is called both when the component is destroyed by Angular AND when the browser event window:beforeunloadis fired. This is a powerful combination!

More about HostListener

@HostListener() is an Angular decorator that can be placed on top of any class method. This decorator takes two arguments: eventName and optionally args. In the above example, we are passing window:beforeunload as the DOM event. This means that Angular will automatically call our method when the DOM event window:beforeunloadis fired. For more information on @HostListener check out the official docs.

If we want to use this to prevent navigation away from a page or component then:

  • Add $event to the @HostListener arguments
  • Call event.preventDefault()
  • Set event.returnValue to a string value of the message we would like the browser to display

An example would look something like this:

@HostListener(‘window:beforeunload’, [‘$event’])
async ngOnDestroy($event) {
if (this.myValueSub) {
this.myValueSub.unsubscribe();
}

await this.authService.logout();

$event.preventDefault();
$event.returnValue = ‘Are you sure you wanna close the page yo?.’;
}

PLEASE NOTE: This is not officially supported by Angular! OnDestroyand ngOnDestroy suggest that there is no input argument on ngOnDestroy allowed. While unsupported, it does in fact still function as normal.

More about window:beforeunload

window:beforeunload is an event fired right before the window is unloaded. More details can be found in the MDN docs.

A couple points to be aware of:

  • This event is currently supported in all major browsers EXCEPT iOS Safari.
  • If you need this functionality in iOS Safari then consider reviewing this Stack Overflow thread.
  • If you are using this event in an attempt to block navigation away you must set the event.returnValue to a string of the message you would like to display. More details in this example.

Conclusion

That brings us to the end of the article, hopefully you have been able to glean some good advice on why and how to use OnDestroy logic in your applications.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on ultimatecourses.com

#angular #angular-js #javascript #typescript #web-development

What is GEEK

Buddha Community

Exploring Life Cycle Hooks in Angular
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Macess  Hulk

Macess Hulk

1567237350

Exploring Life Cycle Hooks in Angular

There’s going to be nothing quite like this available on the web, as we will be promoting best practices, revealing hidden tips and tricks, and getting a real grasp on how and when these hooks are called.


Before we dive into the first installment of the series, let’s review briefly all of the available lifecycle hooks and where they can be used.

Available Lifecycle Hooks:

  • OnChanges
  • OnInit
  • DoCheck
  • AfterContentInit
  • AfterContentChecked
  • AfterViewInit
  • AfterViewChecked
  • OnDestroy

Lifecycle Hooks Can Be Used On:

  • Components
  • Directives

Here is a component with all eight (8) hooks implemented:

import {
  AfterContentChecked,
  AfterContentInit,
  AfterViewChecked,
  AfterViewInit,
  Component,
  DoCheck,
  OnChanges,
  OnDestroy,
  OnInit
} from '@angular/core';

@Component({
selector: ‘app-home’,
templateUrl: ‘./home.component.html’
})
export class HomeComponent
implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
ngOnChanges() {}

ngOnInit() {}

ngDoCheck() {}

ngAfterContentInit() {}

ngAfterContentChecked() {}

ngAfterViewInit() {}

ngAfterViewChecked() {}

ngOnDestroy() {}
}

If you’re like me, you had a few questions after reading the docs. Clean up what? Avoid memory leaks? Hey—that’s not very specific, it sounds like we need to uncover this a bit more. So here we go!

In this article, we will review how to implement OnDestroy, common use cases for OnDestroy, and wrap-up with a bonus enhancement to OnDestroy that will allow it to be executed with browser events.

A Brief Overview

OnDestroy is an Angular lifecycle method, that can hooked into on components and directives in Angular. By defining a specific method named ngOnDestroy on our class, we are telling the Angular runtime, that it should call our method at the appropriate time. This is a powerful and declarative way to add specific cleanup logic to the end of our class lifecycle.

Implementing OnDestroy

As with other Angular lifecycle methods, adding the actual hook for OnDestroy is relatively simple.

Add OnDestroy after the implements keyword

The first step to implementing OnDestroy is to add OnDestroy after the implements keyword on a component or directive.

Here’s a typical component without any lifecycle hooks:

import { Component } from ‘@angular/core’;

@Component({…})
export class MyValueComponent {}

Our first change is to import OnDestroy from Angular’s core and then create a contract with implements OnDestroy:

Fun Fact Time: Technically it’s not required to implement the interface, Angular will call ngOnDestroy regardless, however, it’s very helpful for type-checking, and to allow other developers to quickly identify which lifecycle hooks are in use on this class.
import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {}

Add the ngOnDestroy method to our class

Now that we have added the OnDestroy after implements the TypeScript intellisense will underline the class declaration in red, giving a warning that ngOnDestroy was not found. Let’s fix that by creating our new ngOnDestroy method.

Example Component Before:

import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {}

Example Component After:

import { Component, OnDestroy } from ‘@angular/core’;

@Component({…})
export class MyValueComponent implements OnDestroy {
ngOnDestroy() {
// cleanup logic goes here
}
}

You’ll also note that this lifecycle hook takes no arguments, unlike some of the others we’ll be covering in later articles.

Common Use Cases

As you can see, implementing OnDestroy is fairly straightforward. Now, let’s explore some common use cases for OnDestroy. At the beginning of the article, we mentioned that Angular recommends the following: “Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.” Let’s explore this further.

Avoiding Memory Leaks with OnDestroy

We want to avoid memory leaks, but what are they? According to Google’s definition, a memory leak is “a failure in a program to release discarded memory, causing impaired performance or failure.” Memory leaks are typically created from not understanding how things work and wreak havoc on app performance. Let’s explore an example of one such memory leak – so you’re primed to tackle your OnDestroy logic in future!

A Leaky ShowUserComponent

Let’s imagine a scenario wherein we have a component that has one button. When we click the button a call is made to a method on a AuthService that returns an Observable containing the name of the logged in user. The button click event subscribes to this Observable and displays a window alert with the username.

Here’s how the component might look before implementing OnDestroy:

show-user.component.ts

import { Component } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent {
constructor(private authService: AuthService) {}

showLoggedInUser() {
this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}
}

show-user.component.html

<button (click)=“showLoggedInUser()”>Show Logged In User</button>

At first glance, you might say, “This component looks great, it subscribes to the service and shows an alert on click”. You’d be correct, but what do you think would happen if this ShowUserComponent was used in the AppComponent and displayed with an *ngIf conditionally. Perhaps a scenario exists where the ShowUserComponent is destroyed and then displayed again.

Well, I can tell you what would happen, some really odd, strange behavior. If the component was instantiated, the user clicked the button and alert displayed, then one subscription would be created. Then let’s say, the component was re-created and the user clicked the button again, how times would the alert display? Two times, at least! This is because a second subscription would be created and then fired when the button is clicked.

This is creating the “memory leak” and could quickly get out of hand, with our alert being shown exponentially (just imagine the impact across an entire codebase without cleaning things up properly!). Let’s read on to learn how to plug this memory leak using OnDestroy.

Fixing the Leak on ShowUserComponent

To fix the memory leak we need to augment the component class with an implementation of OnDestroy and unsubscribe from the subscription. Let’s update our component adding the following:

  • Add OnDestroy to the typescript import
  • Add OnDestroy to the implements list
  • Create a class field named myUserSub: Subscription to track our subscription
  • Set this.myUserSub equal to the value of this.authService.getLoggedInUserName().subscription
  • Create a new class method named ngOnDestroy
  • Call this.myUserSub.unsubscribe() within ngOnDestroy if a subscription has been set.
Best Practice: Notice that we are checking if this.myUserSub is “truthy” before attempting to call unsubscribe. This avoids a potential situation wherein the subscription may have never been created, thus preventing a ghastly unsubscribe is not a function error message.

The updated component will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { Subscription } from ‘rxjs’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
}
}

Now we can ensure that our alert will only ever be displayed once per button click.

Great! Now we have some background on ngOnDestroy and how cleaning up memory leaks is the primary use case for this lifecycle method.

Additional Cleanup Logic

Exploring further, we find more examples of use cases for ngOnDestroyincluding making server-side cleanup calls, and preventing user navigation away from our component. Let’s explore these additional scenarios, and how we can enhance ngOnDestroy to meet our needs.

Making NgOnDestroy Async

As with other lifecycle methods in Angular, we can modify ngOnDestroywith async. This will allow us to make calls to methods returning a Promise. This can be a powerful way to manage cleanup activities in our application. As we read on we will explore an example of this.

Adding logic to call AuthService.logout from ngOnDestroy

Let’s pretend that we need to perform a server-side user logout when ShowUserComponent is destroyed. To do so we would update the method as follows:

  • Add async in front of the method name ngOnDestroy
  • Make a call to an AuthService to logout using the await keyword.

Our updated ShowUserComponent will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}

Tada! Now when the component is destroyed an async call will be made to logout the user and destroy their session on the server.

Unsubscribe versus takeUntil

As an alternative to manually calling unsubscribe you could take things a step further and make use of the takeUntil RxJS operator to “short-circuit” the subscription when a value is emitted.

Confused? Well imagine this…

  • Add a new private property to your component named destroyed$. This property will be a ReplaySubject<boolean> = new ReplaySubject(1), meaning it only ever emits one boolean value.
  • Add a .pipe to the this.authService.getLoggedInUserName()subscription
  • Pass takeUntil(this.destroyed$) into the pipe method
  • Update the ngOnDestroy method to push a new value to the destroyed$ subject, using this.destroyed$.next(true)
  • Update the ngOnDestroy method to call complete on the destroyed$ subject.

The finished component will look something like this:

import { Component, OnDestroy } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;
import { ReplaySubject } from ‘rxjs’;
import { takeUntil } from ‘rxjs/operators’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.pipe(takeUntil(this.destroyed$))
.subscribe(username => window.alert(You are logged in as ${username}!));
}

async ngOnDestroy() {
this.destroyed$.next(true);
this.destroyed$.complete();
await this.authService.logout();
}
}

With this new method in place, we no longer need to keep track of each subscription, check for truthy and call unsubscribe. The real power of this comes into play, when we have multiple subscriptions that need to be unsubscribed from. At that point, we would just add the takeUntil to each subscription, and then leave our updated ngOnDestroy to emit the destroyed$ true value to all the subscriptions.

Advanced ngOnDestroy, Browser Events

Ensure Execution During Browser Events

Many developers are surprised to learn that ngOnDestroy is only fired when the class which it has been implemented on is destroyed within the context of a running browser session.

In other words, ngOnDestroy is not reliably called in the following scenarios:

  • Page Refresh
  • Tab Close
  • Browser Close
  • Navigation Away From Page

This could be a deal-breaker when thinking about the prior example of logging the user out on destroy. Why? Well, most users would simply close the browser session or navigate to another site. So how do we make sure to capture or hook into that activity if ngOnDestroy doesn’t work in those scenarios?

Decorating ngOnDestroy with HostListener

TypeScript decorators are used throughout Angular applications. More information can be found here in the official TypeScript docs.

To ensure that our ngOnDestroy is executed in the above mentioned browser events, we can add one simple line of code to the top of ngOnDestroy. Let’s continue with our previous example of ShowUserComponent and decorate ngOnDestroy:

  • Add HostListener to the imports
  • Place @HostListener(‘window:beforeunload’) on top of ngOnDestroy

Our updated ShowUserComponent will look something like this:

import { Component, OnDestroy, HostListener } from ‘@angular/core’;
import { AuthService } from ‘./auth.service’;

@Component({…})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;

constructor(private authService: AuthService) {}

showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(You are logged in as ${username}!));
}

@HostListener(‘window:beforeunload’)
async ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
await this.authService.logout();
}
}

Now our ngOnDestroy method is called both when the component is destroyed by Angular AND when the browser event window:beforeunloadis fired. This is a powerful combination!

More about HostListener

@HostListener() is an Angular decorator that can be placed on top of any class method. This decorator takes two arguments: eventName and optionally args. In the above example, we are passing window:beforeunload as the DOM event. This means that Angular will automatically call our method when the DOM event window:beforeunloadis fired. For more information on @HostListener check out the official docs.

If we want to use this to prevent navigation away from a page or component then:

  • Add $event to the @HostListener arguments
  • Call event.preventDefault()
  • Set event.returnValue to a string value of the message we would like the browser to display

An example would look something like this:

@HostListener(‘window:beforeunload’, [‘$event’])
async ngOnDestroy($event) {
if (this.myValueSub) {
this.myValueSub.unsubscribe();
}

await this.authService.logout();

$event.preventDefault();
$event.returnValue = ‘Are you sure you wanna close the page yo?.’;
}

PLEASE NOTE: This is not officially supported by Angular! OnDestroyand ngOnDestroy suggest that there is no input argument on ngOnDestroy allowed. While unsupported, it does in fact still function as normal.

More about window:beforeunload

window:beforeunload is an event fired right before the window is unloaded. More details can be found in the MDN docs.

A couple points to be aware of:

  • This event is currently supported in all major browsers EXCEPT iOS Safari.
  • If you need this functionality in iOS Safari then consider reviewing this Stack Overflow thread.
  • If you are using this event in an attempt to block navigation away you must set the event.returnValue to a string of the message you would like to display. More details in this example.

Conclusion

That brings us to the end of the article, hopefully you have been able to glean some good advice on why and how to use OnDestroy logic in your applications.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on ultimatecourses.com

#angular #angular-js #javascript #typescript #web-development

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial

Mansi Gandhi

Mansi Gandhi

1625232772

Why Choose AngularJS framework for the enterprise? | Angular development Company - CMARIX

Although Angular JS has bought headlines over the domain of Web application development, its relevance downtime does not offer any guarantee. Since the JavaScript application is the child of Google, its web features may have some value. Angular JS enables the developer to write most of the code in HTML which brings the application together. Such potentiality and simplicity of the program from the Angular Development Company made Angular popular among JavaScripts.

But the real question arises on the integrity and the safety Angular can provide to the industry. Angular regularly updates its libraries to fix security issues over earlier versions. However, the private and customized Angular versions fall back from the latest versions. These versions might lack the crucial security patches. As a piece of advice, developers can share their improvement requests in the community.

Backward compatibility indicates that the updated versions can function with the outdated versions. Hence, it can simplify the migration procedures to the latest Angular version. Some portions of the AngularJS apps need lazy loading to ease the update and to facilitate the transfer of large projects.

Since AngularJS tends to spoil backward compatibility, it might cause future problems in a program.

The Changing Face of Frameworks

There were several ups and downs in the Web application market over the past. A few years ago, SproutCore ruled the throne as a top framework. However, according to Google search trends, BackboneJS later stole the spotlight which again passed over to EmberJS. But, there remains no comparison for AngularJS.

Birthed by Adam Abrons and Misko Hevery, the Brat Tech engineers in 2009, the Angular Development Company AngularJS took a swift transition to open-source. When Misko Hevery joined Google, he continued to develop Angular JS. The platform began to earn its place by December of 2012 according to Google Trends.

In the year 2015, the potential of AngularJS surpassed other frameworks and offered job placements for many developers. However, AngularJS is not entirely without competition as Facebook came up with ReactJS. Hence, there is a race to show which surpasses the other. But, according to Jeff Schroeder, among the native apps, React elevates mobile app development to higher levels.

Continuous Development in Angular JS

AngularJS has high popularity yet, the developers break backward compatibility on a regular basis. Therefore, the supporters of AngularJS have to learn the AngularJS framework again and again. A critic of AngularJS – Danny Tuppeny, points out that the framework is unstable as it offers short-term support. The developers develop the framework every now and then which can puzzle its users. However, a mobile Web developer by the name of Nene Bodonkor indicates another factor. The frameworks become satisfactory and since they fail to keep up with the market requirements, change becomes crucial.

On the contrary, Yehuda Katz, the creator of EmberJS suggests that the fast-paced lifestyle needs to slow down. Therefore, these constant changes can compel people to reduce and balance their pace. Both, ReactJS from Facebook and EmberJS fight to achieve maximum backward compatibility. Such a characteristic helps these frameworks to come to use for an enterprise. But, AngularJS still has its upper hand over its competitors.

The simple-to-learn design of the Angular Framework with various functions

A legacy system includes few characteristics like old technology that are not compatible with the present systems. These systems do not remain available for purchase from distributors or vendors. These legacy systems cannot update nor patch up by themselves as the developer or vendor stops its maintenance.

The CTO of a mobile and Web app development company Monsoon, Michi Kono agreed on the decisions. But he also commented that the core developers at AngularJS miscommunicated the information. As the AngularJS framework has its uses in Google, they can use the platform for legacy versions and supporting enterprises. According to Michi Kono, AngularJS can promise a safe approach for its use in enterprises. The framework of Angular Development Company USA makes learning simple as it lacks strong convention opinions. The framework is easy for developers to learn and Angular has its applications on other parallel technologies. Vast organizations that have a demand for on-scale development and hiring procedures can use the framework to their advantage.

The low level of Angular appears more as a toolbox than a framework. Such an approach makes Angular useful on a wide variety of utility functions. The developer can use the JavaScript framework to add a single website button through a separate framework. Major companies like Google, Facebook and Microsoft aim to improve JavaScript to match entrepreneur requirements. Since AtScript or the typed JavaScript from Google, will form the backbone of AngularJS 2.0, several developers shall prefer to leverage it.

The Best Fit

AngularJS has several promising aspects for developers from different enterprises to try. But the JavaScript framework undergoes several alterations by its developers. Yet, some of the JavaScript frameworks grab the focus of various users for which they remain in maintenance. Therefore, according to Brian Leroux, the Adobe Web developer, there are two options left. Developers can either imprison themselves within vast rewrites with no forward progress. Or Hire angular developers who can focus their attention to optimize the website architecture. Therefore, developers need to stay up-to-date with the current developments in the web application frameworks like AngularJS.

AngularJS frameworks carry lots of potential in real-time markets. But, the developers need to stay up-to-date to tackle the regular changes in its infrastructure.

#hire angular developers #angular #angular web development #angular development company #angular services #angularjs