Daisy Rees

Daisy Rees

1559812749

Top 7 Angular Tips and Tricks

Angular is a JavaScript framework for building web applications, especially single page applications. As a framework, it offers the best practices and tooling to easily develop these web applications. When building with Angular, you’ll be using declarative templates, dependency injection, etc. to power applications that can run on all platforms (web, mobile and desktop).

Angular already outlines its best practices for easy development using the framework, but there might be other tips that you’ve missed that will most likely make development easier or help your application run and load faster. So here are seven tips and tricks to making Angular applications better.

1. Use Services to Handle Side Effects

When building your application, it is always useful to reduce side effects like HTTP requests, time-based events, etc. Abstracting these from the component to services will help reduce the complexity of the component and also ensures the reusability of the service. An example would be fetching data from an external server. You could fetch data within your component like this:

    import { Component } from "@angular/core";
    
    @Component({
      selector: 'app-component',
      template: '<ul> <li *ngFor="let item of items">{{item}}</li> </ul>',
    })
    export class AppComponent implements OnInit{
      constructor(private http: HttpClient){
      }
      items = [];
      
      getItems(){
        return this.http.get('http://server.com/items')
      }
      
      ngOnInit(){
        this.getItems.subscribe(items => this.items = items);
      }
    }

This method used in fetching the items is local to the component and can’t be reused, and if items are being fetched in other components, this whole procedure will be repeated and that’s not very DRY. If multiple network requests are made, the component will be littered with these methods. Let’s refactor this component to use a service for external requests.

    @Injectable({
      providedIn: 'root'
    })
    export class ItemService {
      constructor (private http: HttpClient) {}
    
      getItems() {
        return this.http.get('http://server.com/items');
      }
    }

Then we’ll make use of it in the component:

    import { Component } from "@angular/core";
    
    @Component({
      selector: 'app-component',
      template: '<ul> <li *ngFor="let item of items">{{item}}</li> </ul>',
    })
    export class AppComponent implements OnInit{
      constructor(private itemsService: ItemsService){
      }
      items = [];
      
      ngOnInit(){
        this.itemsServices.getItems().subscribe(items => this.items = items);
      }
    }

This service can be used to fetch items application-wide.

2. ng add

This utility, introduced in Angular version 6, can be used to add a published package to your work environment, and it’ll run schematics in the background to update the functionality of your application. When downloading a package using this command, it also installs extra dependencies it needs to run, like polyfills, etc. Your application can be converted to a progressive web application using service workers and providing offline functionality using the command.

You can implement progressive web application features in your application by running the following command:

 ng add @angular/pwa 

Or if you wish to add a touch of Material Design in your application, you can add the Angular Material library

 ng add @angular/material 

3. Web Components

From Angular version 6 onward, you can develop custom native elements that can be used outside Angular. This can be done using a package introduced by Angular called Angular Elements (@angular/elements). This package provides a way to createCustomElements and polyfills to support browsers that aren’t compatible with web components. With this package, you can package your favourite components and use them within other frameworks like React, Vue, etc.

To get started building custom native elements in Angular, install the Angular Elements package in your application using the following command:

    ng add @angular/elements --name=<your_project_name>

You can follow the quick tutorial in the official Angular documentation to get started.

4. Aliases for Import Statements

This very useful feature is supported out of the box in Angular. I’m sure you’ve encountered instances where imports in your applications are just messy and difficult to read. You have something like:

    import { ThatComponent } from '../../../components/this-component/child-component'
    import { ThisService } from '../../../../services/this-service'

I’m sure it would be more helpful to have aliases for the components and services paths – this would make these imports relatively easy to read and import.

When working with React, I’ve researched how to achieve this, but most solutions involve ejecting your application, which doesn’t really sound pleasing. Well, to achieve this in your Angular application, all you need to do is to update the tsconfig.json file:

    {
      "compileOnSave": false,
      "compilerOptions": {
        "baseUrl": "src",
        "paths": {
          "@components": "app/components",
          "@services": "app/services",
        },
        "..."
      }
    }

What happened here is that the default value of the baseUrl property ./ was updated to point to the src directory. Then we added a new property called paths, which is an object containing key values pairs representing aliases defined for paths in our application. Aliases were defined for the components folder and the services folder. Now if we want to attempt the imports in the previous example, we’ll do this:

    import { ThatComponent } from '@components/this-component/child-component';
    import { ThisService } from '@services/this-service';

This is way cleaner and easier to read than the previous example. If you’ve not booted up your editor to do this for your application already, then you should get to it.

5. Safe Navigation Operator for String Interpolation

When working with objects in Angular templates, you encounter situations where variables are declared without default values – the variable is just presented as a type definition. When trying to access a property on the variable that isn’t readily available, Angular will throw an error saying the variable is undefined.

For example, your template looks like this, you’re reading the name property of a student object:

 

{{ student.name }}

And this was how the variable was declared in the component file:

    interface Student {
      name: String;
      age: Number:
    }
    
    @Component({
      selector: 'app-component',
    })
    export class AppComponent{
      student: Student;
    }

Angular will throw an error here.

Using the safe navigation operator, we can safeguard the name property against any null and undefined values. The safe navigation operator in Angular is this syntax ?., and we can update the template to use this:

 

{{ student?.name }}

When you run this, Angular doesn’t throw any errors and your console is clear. Another useful technique of avoiding this error is using the and (&&) operator to check if the value exists before reading the property path. We can update the example to use this syntax:

 

{{ student && student.name }}

If the value doesn’t exist, Angular will avoid evaluating the expression and nothing is rendered between the tags.

6. Handle Errors Properly with an Error Handler

Angular comes packed with an exception handling service that can be used to manage errors application-wide. When the service detects errors, it catches the error and logs it to the console. This service can be extended to add additional features unique to our application like logging the error using an error monitoring platform or sending the errors to your server for analytics.

The Error Handler is pretty easy to extend: We need to create a class that extends the properties of the ErrorHandler and overrides the built in handleError method used for displaying errors.

Create a file called error-handler.class.ts:

    import {ErrorHandler} from '@angular/core';
    // A fake error monitoring library
    import ErrorClient from '@error-reporters/core';
    
    // Initialize the report library
    const reporter = new ErrorClient();
    
    export class AppErrorHandler extends ErrorHandler {
        constructor(private errorService: ErrorService){
            super(false);
        }
    
        public handleError(error: any): void {
            reporter.sendReport(error)
            super.handleError(error);
        }
    }

In the snippet above, we made use of a fictional error reporting and monitoring library called @error-reporters. After extending the ErrorHandler service, we will report errors emanating from the application in the handleError method before handling the error with the ErrorHandler’s handleError method.

After that, we should register our custom AppErrorHandler in app.module.ts:

    @NgModule({
        declarations: [ AppComponent ],
        imports: [ BrowserModule ],
        bootstrap: [ AppComponent ],
        providers: [
            {provide: ErrorHandler, useClass: AppErrorHandler}
        ]
    })

You can read more on the default error handler by Angular here.

7. Lazy Load Non-Vital Components

When working on fairly large applications or starting up one, it will be helpful to ensure that components not needed for the initial render of your application are lazy loaded. Lazy loaded in the sense that they’re loaded on demand. For example, when a user navigates away from the initial view of the application, a network request is made to load the destination route. Lazy loading can effectively reduce the bundle size of your application, thus reducing the load time of the application on the browser.

Lazy loading components starts with creating a feature module in your application, the feature module will house the components, services, providers, etc. attached it. The feature module is then loaded in the root routing module of the application. Look at the example below:

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FeatureRoutingModule } from './feature-routing.module';
    import { FeatureComponent } from './feature/feature.component';
    
    @NgModule({
      imports: [
        CommonModule,
        FeatureRoutingModule
      ],
      declarations: [FeatureComponent]
    })
    export class FeatureModule { }

This feature module FeatureModule contains a single component FeatureComponent and a routing module FeatureRoutingModule attached to it.

To lazy load this component, we’ll register the feature module’s routing module in the application’s root module:

    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { BrowserModule } from '@angular/platform-browser';
    import { RouterModule } from '@angular/router';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot([
          {
            path: 'feature',
            loadChildren: './feature/feature.module#FeatureModule'
          }
        ])
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

With this simple step, a separate bundle will be built apart from the main app bundle. This bundle will be loaded when the user navigates to the /feature route. The experience might be a bit unpleasant because the user will need to wait for the route’s bundle to be loaded, and this might take a while depending on the size of the bundle.

To fix this issue, we’ll prefetch the other bundles in the background once the initial page has been loaded fully. We can do this using a built-in flag provided by Angular called the preloadStrategy. This tells Angular which strategy to use when loading lazied bundles.

Let’s update the current implementation to use the PreloadAllModules strategy:

    import { NgModule } from '@angular/core';
    ...
    import { RouterModule, PreloadAllModules } from '@angular/router';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
       ...
      ],
      imports: [
        ...
        RouterModule.forRoot([
          {
            path: 'feature',
            loadChildren: './feature/feature.module#FeatureModule'
          }
        ], {preloadStrategy: PreloadAllModules})
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

With this update, Angular will handle prefetching of feature bundles in the background for easy navigation.

Conclusion

Angular is a framework which means it has its way of doing things and producing results. It comes with so many features both popular and unknown, the easiest way to discover tricks to achieve difficult tasks using Angular is to use Angular a lot more and research more in the process. The tips and tricks listed above don’t fully cover the extent of what can be done using Angular’s extensive features.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Web Developer Bootcamp

Angular 8 is coming

MEAN Stack Angular 8 CRUD Web Application

Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

#angular #angular-js

What is GEEK

Buddha Community

Top 7 Angular Tips and Tricks
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Jack Salvator

Jack Salvator

1608113009

New Angular 7 Features With Example - Info Stans

What is new in New Angular 7? New Angular 7 features have turned out as a powerful release that really brought advancement in the application development structure.

Here, we have listed new Angular 7 features with examples and write the difference between Angular 6 and Angular 7.

  • Bundle Budget
  • Virtual Scrolling
  • Error Handling
  • Documentation Updates
  • Application Performance
  • Native Script
  • CLI Prompts
  • Component in angular 7
  • Drag and Drop
  • Angular Do-Bootstrap

Read more: Angular 7 Features With Example

#angular 7 features #what’s new angular 7 #new angular 7 features #angular 7 features with examples

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

Top Enterprise Angular Web Apps Development Company in USA

AppClues Infotech is one of the leading Enterprise Angular Web Apps Development Company in USA. Our dedicated & highly experienced Angular app developers build top-grade Angular apps for your business with immersive technology & superior functionalities.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top enterprise angular web apps development company in usa #enterprise angular web apps development #hire enterprise angular web apps developers #best enterprise angular web app services #custom enterprise angular web apps solution #professional enterprise angular web apps developers

Clara  Gutmann

Clara Gutmann

1598727360

Angular 8 Updates And Summary of New Features

Angular 8 Updates And Summary of New Features is today’s topic. Angular 8 arrives with an impressive list of changes and improvements including the much-anticipated Ivy compiler as an opt-in feature. You can check out  Angular 7 features and updates if you have not seen yet. In this blog, we have written some articles about  Angular 7 Crud,  Angular 7 Routing,  Angular ngClass,  Angular ngFor.

Angular 8 Updates And Summary

See the following updates.

TypeScript 3.4

Angular 8.0 is now supported TypeScript 3.4, and even requires it, so you will need to upgrade.

You can look at what  TypeScript 3.3 and  TypeScript 3.4 brings on the table on official Microsoft blog.

#angular #typescript #angular 7 crud #angular 7 routing #angular 8