The introduction to Angular you may be missing

Angular is a framework to develop Single Page Applications, based on TypeScript. It is developed by the Angular Team in Google, and was launched in 2016 with a stable version 2. It is a complete rewrite of AngularJS, another framework developed by Google.

What is Angular

Angular is a framework to develop Single Page Applications, based on TypeScript. It is developed by the Angular Team in Google, and was launched in 2016 with a stable version 2. It is a complete rewrite of AngularJS, another framework developed by Google.

Angular use common features from server side frameworks, such as Modules, Dependency Injection, a typed language, and recommends a folder-by-feature structure, making several decisions for you, including design and architectural decisions. This things makes a bit harder to enter to Angular development, and you may find you self looking for the Angular way when doing the most simple thing. But they also allows a easy scaling of the application, and a consistent development in a large team of developers.

Single page application architecture

Every application have its own architecture, but there are certain parts that all single page applications would eventually need.

  • User Interface Layer
  • HTTP library
  • Logic
  • Router
  • State manager

This are, somehow, the most common pieces that you would need to build a complete SPA.ref

Another way to look at a SPA architecture can be through layers: ref

  • View
  • Services
  • Store
  • Domain

You can see the relation between both approaches.

What makes Angular a framework?

If you take a look a the architecture, you will notice that Angular actually have a module, or library, for each part of the architecture.

This is what makes Angular a framework, the fact that it is composed by several modules that fills the needs to develop a Single Page Application.

In comparison with React, or Vue, they only represents the View part of the architecture, or the User Interface, leaving you on your own to choose the best library for the another layers of the application.

  • Components for the User Interface Layer
  • HttpClient as the HTTP library
  • Component and Services for the Logic
  • Router for the Routing
  • Services as State manager

Additionally you have other libraries to help you in the development of the application, such as:

  • Animations for javascript animations
  • Forms for template driven forms
  • ReactiveForms for model driven forms
  • i18n for internalization, and localization
  • Pipes for template data transformations
  • Platform modules for different target platforms (eg: Browser, Webworker)
  • Guards for authentication and authorization management
  • CLI tool for fast setup, testing and build
  • Many more...
Learning Angular

Angular have a s shaped learning curve, meaning that you probably will start really slow, as you need to learn how to use several tools aside from the framework itself that is actually quite large and full of features. You will need some time to have experience with it, but after that, you probably wont need to learn anything else.

To start with Angular, there are several technologies that may afraid you at first:

  • Typescript
  • ES2015 (and ES2016, ES2017, ES2018)
  • Decorators
  • Observables
  • rxjs
  • Lazy Loading
  • AOT
  • Dependency Injection
  • And list goes on...

It's totally normal to feel afraid by those, I mean... What the heck Angular? Why can't you just be normal?

And... the Angular Style Guide.

This design choices are valuable when developing a large application, but they will benefit you even in a small application.

If you want a complete introduction to the Angular world, the Tour of Heroes tutorial is the place to go. It is constantly updated, and will have the most used feature covered in a really step-by-step explanation.

Now I will give a small introduction of the most important, and most controversial tools used by Angular.

Typescript

This is the most common argument against Angular, and actually you can develop an Angular application without using Typescript. But, here is why you probably will better with it:

  • Automatic Dependency Injection
  • Advantages of ES2015+
  • Decorators
  • IDE-like experience
ES2015+

Some of us are still using plain ES5 to develop an application. Well, almost ES5, as we always are using something on top of it, as lodash, jquery, and other things. But build tools, as Webpack or Rollup, are now quite common, and you should not be uncomfortable using them. Using features of ES2015+, you probably won't even need jQuery or lodash.

Decorators

The decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.ref In Javascript, Decorator proposal was in Stage 1 when Angular Team announce they will be using decorators in ATScript, a short lived language that extends Typescript. Microsoft accepted to introduce many of ATScript features in Typescript, to be used by the Angular Team in the development of Angular 2. It is now in Stage 2, but its specification have change. Typescript still use the previous specification, as it is used by Angular.

The most important thing to understand about Decorators, is that at the end, they are only functions, that add a behavior in a class, property or method. They are really easy to use, to learn, and to develop. If you are have a React background, you can think they are some kind of high order function.

Observables (Reactive Programming and rxjs)

This actually should be the harder thing to learn, but one of the things that you won't live without afterward. Reactive programming is a programming paradigm to deal with data in an asynchronous fashion, that allows to get the last value of a computed operation. Reactive programming implementation in Javascript are going to be Observables currently are on Stage 1, soon to be on Stage 2. This means that in a couple of years, probably, all major evergreen browsers will support this natively.

rxjs is a library that implements its own version of the Observable, and it's used heavily by Angular, specially to deal with data fetching as HttpClient instance will return an observable, and to emit events, as EventEmitter extends from Observable.

To make your learning path easy, every instance of rxjs Observable have a toPromise method, to resolve the value of the observable as a promise afterit completes. This is tricky when you are dealing with user events, as most of then will never complete, but you can use this approach to deal with data fetching, as they will be complete after the request. Still it's better to understand rxjs observables, and how to use its operators.

Lazy loading, AoT, Dependency Injection... And the Angular Style Guide.

Dependency injection is something that you should need to know when developing with Angular, but this is somewhat common in other frameworks, specially in server side frameworks. Still, if you don't know what dependency injection is, very quickly, is the ability to ask for an instance of a class, and have it. This a really simple way to see it, but at the end, that's actually what it is.

For everything else, you have MasterCard. Ok, you may not. But don't needto know all this things. Sure, lazy loading and AoT will help you to reduce the bundle size of the application, but first, build that application. It's easy to add up those things afterward, and they are not needed to start developing.

About the Angular Style Guide, well, that's something I like about Angular, they have it's own way to do things. When you have time, give it a look. Sure it will help you when dealing with a large application.

ngrx

I will mention ngrx as this is the only state library, in my own opinion, that actually have a deep integration with Angular. This is really easy to use, after you understand the flux pattern. I even learn this by doing a React+Redux course in EggHead. So, yeah. The how to use is Redux.

Developing an Angular application

I will cheat here, and will use Angular-cli.

$ npm install -g @angular/cli
$ ng new demo-app

This will generate all the necessary files to develop an Angular application, and even setup Karma as unit testing framework, and Protractor for the e2e testing. To start the new application, I will use Angular CLI again.

$ npx ng serve
// or
$ npm start
Angular-CLI creates several scripts in package, to serve, build, and test.

This will serve the Angular application using a Webpack Dev Server underneath. The Angular-CLI is a super powerful tool, that will allow you to create new projects, components, services, pipes, models, and almost anything you will need to develop an Angular application.

You have to notice that using Angular-CLI have a downside, you can't configure directly the build configuration. This is a design decision, and it does have a motive, but still. If you want complete control over the build process, that you should not want because the CLI will do almost everything for you, but if you want, you just need to ng eject the project.

Using Angular-CLI does not stop you to integrate the Angular application with other frameworks as Electron, NativeScript, or Ionic.

What's next for Angular?

So far we have see several key features that Angular have, but there are many things to come. Some of the following features are now partially available or in a beta version, some of them will arrive in the next version of Angular, and some of them will be following after that.

  • Angular Elements - Use Angular Components as Custom Web Components
  • Ivy Renderer - Reduce the bundle size of the Angular application, and increase the rendering performance.
  • Component Dev Kit (CDK) - High performance set of Angular components to include with your CSS framework of choice.
  • Bazel - A better build tool.
  • Schematics - File code transformations for Angular CLI projects.

Of curse, the road-map also includes several optimizations and bug fixes, but this are the new features that you will be using in your next projects.

That's all folks!

Thanks for reading. I hope you like it. Share it with your friends, your coworkers, your PM and let me know what you think in the comments.


By : Michael De Abreu


What are the best alternatives for angular js?

<img src="https://moriohcdn.b-cdn.net/193902114c.png">There are numerous frameworks and libraries used across the globe. If not angular, there are platforms like React, Vue, Aurelia and so on for app development.

There are numerous frameworks and libraries used across the globe. If not angular, there are platforms like React, Vue, Aurelia and so on for app development.

Angular 8 Node & Express JS File Upload

Angular 8 Node & Express JS File Upload

In this Angular 8 and Node.js tutorial, we are going to look at how to upload files on the Node server. To create Angular image upload component, we will be using Angular 8 front-end framework along with ng2-file-upload NPM package; It’s an easy to use Angular directives for uploading the files.

In this Angular 8 and Node.js tutorial, we are going to look at how to upload files on the Node server. To create Angular image upload component, we will be using Angular 8 front-end framework along with ng2-file-upload NPM package; It’s an easy to use Angular directives for uploading the files.

We are also going to take the help of Node.js to create the backend server for Image or File uploading demo. Initially, we’ll set up an Angular 8 web app from scratch using Angular CLI. You must have Node.js and Angular CLI installed in your system.

We’ll create the local server using Node.js and multer middleware. Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. Once we are done setting up front-end and backend for our File uploading demo then, we’ll understand step by step how to configure file uploading in Angular 8 app using Node server.

Prerequisite

In order to show you Angular 8 File upload demo, you must have Node.js and Angular CLI installed in your system. If not then check out this tutorial: Set up Node JS

Run following command to install Angular CLI:

npm install @angular/cli -g

Install Angular 8 App

Run command to install Angular 8 project:

ng new angular-node-file-upload

# ? Would you like to add Angular routing? No
# ? Which stylesheet format would you like to use? CSS
cd angular-node-file-upload

Show Alert Messages When File Uploaded

We are going to install and configure ngx-toastr an NPM package which helps in showing the alert message when the file is uploaded on the node server.

npm install ngx-toastr --save

The ngx-toastr NPM module requires @angular/animations dependency:

npm install @angular/animations --save

Then, add the ngx-toastr CSS in angular.json file:

"styles": [
    "src/styles.css",
    "node_modules/ngx-toastr/toastr.css"
]

Import BrowserAnimationsModule and ToastrModule in app.module.ts file:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
 
@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot() // ToastrModule added
  ]
})

export class AppModule { }

Install & Configure ng-file-upload Directive

In this step, we’ll Install and configure ng-file-upload library in Angular 8 app. Run command to install ng-file-upload library.

npm install ng2-file-upload

Once the ng2-file-upload directive is installed, then import the FileSelectDirective and FormsModule in app.module.ts. We need FormsModule service so that we can create the file uploading component in Angular.

import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    FileSelectDirective
  ],
  imports: [
    FormsModule
  ]
})

export class AppModule { }

Setting Up Node Backend for File Upload Demo

To upload the file on the server, we need to set up a separate backend. In this tutorial, we will be using Node & Express js to create server locally along with multer, express js, body-parser, and dotenv libraries.

Run command to create backend folder in Angular app’s root directory:

mkdir backend && cd backend

In the next step, create a specific package.json file.

npm init

Run command to install required dependencies:

npm install express cors body-parser multer dotenv --save

In order to get rid from starting the server again and again, install nodemon NPM package. Use –-save-dev along with the npm command to register in the devDependencies array. It will make it available for development purpose only.

npm install nodemon --save-dev

Have a look at final pacakge.json file for file upload demo backend:

{
  "name": "angular-node-file-upload",
  "version": "1.0.0",
  "description": "Angualr 8 file upload demo app",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Digamber Rawat",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.1",
    "multer": "^1.4.1"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
}

Create a file by the name of server.js inside backend folder:

Configure Server.js

To configure our backend we need to create a server.js file. In this file we’ll keep our backend server’s settings.

touch server.js

Now, paste the following code in backend > server.js file:

const express = require('express'),
  path = require('path'),
  cors = require('cors'),
  multer = require('multer'),
  bodyParser = require('body-parser');

// File upload settings  
const PATH = './uploads';

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, PATH);
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

let upload = multer({
  storage: storage
});

// Express settings
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

app.get('/api', function (req, res) {
  res.end('File catcher');
});

// POST File
app.post('/api/upload', upload.single('image'), function (req, res) {
  if (!req.file) {
    console.log("No file is available!");
    return res.send({
      success: false
    });

  } else {
    console.log('File is available!');
    return res.send({
      success: true
    })
  }
});

// Create PORT
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
  console.log('Connected to port ' + PORT)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

Now, while staying in the backend folder run the below command to start the backend server:

nodemon server.js

If everything goes fine then you’ll get the following output:

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Connected to port 8080

Create Angular 8 File Upload Component

In this last step, we are going to create a file upload component in Angular 8 app using Express js API.

Get into the app.component.ts file and include the following code:

import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { ToastrService } from 'ngx-toastr';

const URL = 'http://localhost:8080/api/upload';

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

export class AppComponent implements OnInit {
  public uploader: FileUploader = new FileUploader({
    url: URL,
    itemAlias: 'image'
  });

  constructor(private toastr: ToastrService) { }

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };
    this.uploader.onCompleteItem = (item: any, status: any) => {
      console.log('Uploaded File Details:', item);
      this.toastr.success('File successfully uploaded!');
    };
  }

}

Go to app.component.html file and add the given below code:

<div class="wrapper">
  <h2>Angular Image Upload Demo</h2>

  <div class="file-upload">
    <input type="file" name="image" ng2FileSelect [uploader]="uploader" accept="image/x-png,image/gif,image/jpeg" />
    <button type="button" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
      Upload
    </button>
  </div>

</div>

Now, It’s time to start the Angular 8 app to check out the File upload demo in the browser. Run the following command:

ng serve --open

Make sure your NODE server must be running to manage the backend.

When you upload the image from front-end you’ll see your image files are saving inside the backend > uploads folder.

Conclusion

In this Angular 8 tutorial, we barely scratched the surface related to file uploading in a Node application. There are various other methods available on the internet through which you can achieve file uploading task quickly. However, this tutorial is suitable for beginners developers. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

Angular JS Development Company

If you’re finding AngularJS Development Company for consultation or Development, your search ends here at Data EximIT 

🔗 Click here to know more: AngularJS Development