Build a Basic CRUD App with Angular and Node

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
In recent years, single page applications (SPAs) have become more and more popular. A SPA is a website that consists of just one page. That lone page acts as a container for a JavaScript application. The JavaScript is responsible for obtaining the content and rendering it within the container. The content is typically obtained from a web service and RESTful APIs have become the go-to choice in many situations. The part of the application making up the SPA is commonly known as the client or front-end, while the part responsible for the REST API is known as the server or back-end. In this tutorial, you will be developing a simple Angular single page app with a REST backend, based on Node and Express.
You’ll be using Angular as it follows the MVC pattern and cleanly separates the View from the Models. It is straightforward to create HTML templates that are dynamically filled with data and automatically updated whenever the data changes. I have come to love this framework because it is very powerful, has a huge community and excellent documentation.
For the server, you will be using Node with Express. Express is a framework that makes it easy to create REST APIs by allowing to define code that runs for different requests on the server. Additional services can be plugged in globally, or depending on the request. There are a number of frameworks that build on top of Express and automate the task of turning your database models into an API. This tutorial will not make use of any of these in order to keep this focused.
Angular encourages the use of TypeScript. TypeScript adds typing information to JavaScript and, in my opinion, is the future of developing large scale applications in JavaScript. For this reason, you will be developing both client and server using TypeScript.
Here are the libraries you’ll be using for the client and the server:

Angular: The framework used to build the client application
Okta for Authorisation: A plugin that manages single sign-on authorization using Okta, both on the client and the server
Angular Material: An angular plugin that provides out-of-the-box Material Design
Node: The actual server running the JavaScript code
Express: A routing library for responding to server requests and building REST APIs
TypeORM: A database ORM library for TypeScript

Start Your Basic Angular Client Application
Let’s get started by implementing a basic client using Angular. The goal is to develop a product catalog which lets you manage products, their prices, and their stock levels. At the end of this section, you will have a simple application consisting of a top bar and two views, Home and Products. The Products view will not yet have any content and nothing will be password protected. This will be covered in the following sections.
To start you will need to install Angular. I will assume that you already have Node installed on your system and you can use the npm command. Type the following command into a terminal.
npm install -g @angular/cli@7.0.2

Depending on your system, you might need to run this command using sudo because it will install the package globally. The angular-cli package provides the ng command that is used to manage Angular applications. Once installed go to a directory of your choice and create your first Angular application using the following command.
ng new MyAngularClient

Using Angular 7, this will prompt you with two queries. The first asks you if you want to include routing. Answer yes to this. The second query relates to the type of style sheets you want to use. Leave this at the default CSS.
ng new will create a new directory called MyAngularClient and populate it with an application skeleton. Let’s take a bit of time to look at some of the files that the previous command created. At the src directory of the app, you will find a file index.html that is the main page of the application. It doesn’t contain much and simply plays the role of a container. You will also see a style.css file. This contains the global style sheet that is applied throughout the application. If you browse through the folders you might notice a directory src/app containing five files.
app-routing.module.ts
app.component.css
app.component.html
app.component.ts
app.component.spec.ts
app.module.ts

These files define the main application component that will be inserted into the index.html. Here is a short description of each of the files:

app.component.css file contains the style sheets of the main app component. Styles can be defined locally for each component
app.component.html contains the HTML template of the component
app.component.ts file contains the code controlling the view
app.module.ts defines which modules your app will use
app-routing.module.ts is set up to define the routes for your application
app.component.spec.ts contains a skeleton for unit testing the app component

I will not be covering testing in this tutorial, but in real life applications, you should make use of this feature. Before you can get started, you will need to install a few more packages. These will help you to quickly create a nicely designed responsive layout. Navigate to the base directory of the client, MyAngularClient, and type the following command.
npm i @angular/material@7.0.2 @angular/cdk@7.0.2 @angular/animations@7.0.1 @angular/flex-layout@7.0.0-beta.19

The @angular/material and @angular/cdk libraries provide components based on Google’s Material Design, @angular/animations is used to provide smooth transitions, and @angular/flex-layout gives you the tools to make your design responsive.
Next, create the HTML template for the app component. Open src/app/app.component.html and replace the content with the following.

Link: https://developer.okta.com/blog/2018/10/30/basic-crud-angular-and-node

Best of DZone: Angular Tutorials for Beginners and Experts Alike

Angular is a widely popular framework for building web applications, especially single page applications (SPAs). Earlier this year, 55% fo the Stack Overflow community said they loved coding in Angular. That’s a lot of folks! Given the huge demand for Angular in the wider developer community, as well as in our own community here at DZone, we put together this post that contains the best Angular tutorials DZone has published over the years. Enjoy! Angular Tutorials  AngularJS: Different Ways to Using Array Filters by Siva Prasad Reddy Katamreddy. An oldie but a goodie, this tutorial walks you through several different methods of interacting with data stored in variable arrays in the AngularJS framework. 

Link: https://dzone.com/articles/best-of-dzone-angular-tutorials-for-beginners-and?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

CSS and PWAs: Some Tips for Building Progressive Web Apps

In recent years we’ve seen a number of major shifts in the online experience, mostly coming from the proliferation of mobile devices. The evolution of the Web has taken us from single versions of a website, to desktop versus mobile versions, to responsive sites that adapt according to screen size, then to native mobile apps, which either recreate the desktop experience as a native app, or act as a gateway to the responsive version.
The latest iteration of all of this is the progressive web app (PWA). A PWA is a software platform that aims to combine the best of both the Web and the native experience for website/app users.
In this article on CSS and PWAs, we’re going to discuss a number of techniques that can be used when creating the CSS required for the development of PWAs.
What are PWAs?
There are three main features of a PWA. As you’ll see, what makes a web app progressive is the “fixing” of problems typically associated with web apps, by adopting some of the techniques used by native apps to resolve these issues.

Reliable. A PWA should reliably load like a native app (no matter the state of the network). This is contrary to a web page, which typically does not load if the device is disconnected from the network.

Fast. The performance of a PWA should be independent of such things as geography, network speed, load or other factors that are beyond the control of the end user.

Engaging. PWAs should mimic the native app’s immersive, full-screen experience without requiring the need of an app store, even supporting such features as push notifications.

There are other features PWA features, but for now, we’ll keep to the most important ones described above.
Google has been at the forefront of pushing these kind of apps, but the adoption of PWAs has been picking up with vendors and plenty of other companies on the Web helping the adoption and embracing the concept of PWAs.
The following are comments from Itai Sadan, CEO of Duda, who was present at Cloudfest 2018:

Progressive web apps represent the next great leap in the evolution of web design and online presence management … they take the best aspects of native apps, such as a feature-rich experience and the ability to be accessed offline, and incorporate them into responsive websites. This creates an incredible web experience for users without the need to download anything onto their device.
Anyone providing web design services to clients is going to want to offer PWAs because over time, just like with mobile and responsive web design, it will become the industry standard.

What is Required for Developing PWAs?
Developing a PWA is not different from developing a standard web application, and it may be possible to upgrade your existing codebase. Note that for deployment, HTTPS is a requirement, although you can do testing on the localhost. The requirements for an app to become a PWA are discussed below.
1. Create a Manifest File
PWAs must be available to install directly via a website which has been visited, meaning there’s no need for a third-party app store to get the app installed.
To enable this, the app needs to provide a manifest.json file — a JSON file that allows the developer to control how the PWA appears, what needs to be launched and other parameters.
A typical manifest file appears below. As we can see, the properties are setting a number of look-and-feel settings that will be used on the home screen of the device where the app will be installed.

The styling of the PWA starts from the manifest file, but there’s no real CSS involved in this part. It’s just straight up properties, which define the application’s name, icons, primary colors, etc.
2. Using a Service Worker
A service worker is essentially a specific type of web worker, implemented as a JavaScript file that runs independently of the browser — such that it’s able to intercept network requests, caching or retrieving resources from the cache, and delivering push messages as necessary.
The service worker is what makes the PWA truly offline capable.
3. Install the Site Assets, Including CSS
The first time the Service worker is registered, an install event is triggered. This is where all of the site assets are installed, including any CSS, JS and other media and resource files required by the application:
self.addEventListener(‘install’, function(e) {
e.waitUntil(
caches.open(‘airhorner’).then(function(cache)
{
return cache.addAll([
‘/’,
‘/index.html’,
‘/index.html?homescreen=1’,
‘/?homescreen=1’,
‘/styles/main.css’,
‘/scripts/main.min.js’,
‘/sounds/airhorn.mp3’
]);
})
);
});

Developing PWAs is not very different from developing web apps, as long as the fundamental requirements have been met.
This is where the CSS starts to get involved, with the files defined that will be used to style the progressive web app.
The post CSS and PWAs: Some Tips for Building Progressive Web Apps appeared first on SitePoint.

Link: https://www.sitepoint.com/pwa-css-considerations/

10 Essential TypeScript Tips and Tricks for Angular Devs

In this article, we’ll dive into a set of tips and tricks that should come in handy in every Angular project and beyond when dealing with TypeScript.
In recent years, the need for static typing in JavaScript has increased rapidly. Growing front-end projects, more complex services, and elaborate command-line utilities have boosted the need for more defensive programming in the JavaScript world. Furthermore, the burden of compiling an application before actually running it hasn’t seen as a weakness, but rather as an opportunity. While two strong parties (TypeScript and Flow) have emerged, a lot of trends actually indicate that only one may prevail — TypeScript.
Besides the marketing claims and commonly known properties, TypeScript has an amazing community with very active contributors. It also has one of the best teams in terms of language design behind it. Led by Anders Hejlsberg, the team has managed to fully transform the landscape of large-scale JavaScript projects to be nearly an exclusively TypeScript-powered business. With very successful projects such as VSTS or Visual Studio Code, Microsoft themselves is a strong believer in this technology.
But it’s not only the features of TypeScript that make the language appealing, but also the possibilities and frameworks that TypeScript is powering. Google’s decision to fully embrace TypeScript as their language of choice for Angular 2+ has proven to be a win-win. Not only did TypeScript gain more attention, but also Angular itself. Using static typing, the compiler can already give us informative warnings and useful explanations of why our code will not work.
TypeScript Tip 1: Supply Your Own Module Definitions
TypeScript is a superset of JavaScript. As such, every existing npm package can be utilized. While the TypeScript eco-system is huge, not all libraries are yet delivered with appropriate typings. Even worse, for some (smaller) packages not even separate declarations (in the form of @types/{package}) exist. At this point, we have two options:

bring in legacy code using TypeScript tip 7
define the API of the module ourselves.

The latter is definitely preferred. Not only do we have to look at the documentation of the module anyway, but typing it out will prevent simple mistakes during development. Furthermore, if we’re really satisfied with the typings that we just created, we can always submit them to @types for including them on npm. As such, this also rewards us with respect and gratefulness from the community. Nice!
What’s the easiest way to supply our own module definitions? Just create a module.d.ts in the source directory (or it could also be named like the package — for example, unknown-module.d.ts for an npm package unknown-module).
Let’s supply a sample definition for this module:
declare module ‘unknown-module’ {
const unknownModule: any;
export = unknownModule;
}

Obviously, this is just the first step, as we shouldn’t use any at all. (There are many reasons for this. TypeScript tip 5 shows how to avoid it.) However, it’s sufficient to teach TypeScript about the module and prevent compilation errors such as “unknown module ‘unknown-module’”. The export notation here is meant for the classic module.exports = … kind of packages.
Here’s the potential consumption in TypeScript of such a module:
import * as unknownModule from ‘unknown-module’;

As already mentioned, the whole module definition is now placed in the type declaration of the exported constant. If the exported content is a function, the declaration could look like this:
declare module ‘unknown-module’ {
interface UnknownModuleFunction {
(): void;
}
const unknownModule: UnknownModuleFunction;
export = unknownModule;
}

Of course, it’s also possible to use packages that export functionality using the ES6 module syntax:
declare module ‘unknown-module’ {
interface UnknownModuleFunction {
(): void;
}
const unknownModule: UnknownModuleFunction;
export const constantA: number;
export const constantB: string;
export default unknownModule;
}

TypeScript Tip 2: Enum vs Const Enum
TypeScript introduced the concept of enumerations to JavaScript, which did represent a collection of constants. The difference between
const Foo = {
A: 1,
B: 2,
};

and
enum Foo {
A = 1,
B = 2,
}

is not only of syntactical nature in TypeScript. While both will be compiled to an object (i.e., the first one will just stay as is, while the latter will be transformed by TypeScript), the TypeScript enum is protected and contains only constant members. As such, it would not be possible to define its values during runtime. Also, changes of these values will not be permitted by the TypeScript compiler.
This is also reflected in the signature. The latter has a constant signature, which is similar to
interface EnumFoo {
A: 1;
B: 2;
}

while the object is generalized:
interface ConstFoo {
A: number;
B: number;
}

Thus we wouldn’t see the values of these “constants” in our IDE. What does const enum now give us? First, let’s look at the syntax:
const enum Foo {
A = 1,
B = 2,
}

This is actually the same — but note, there’s a const in front. This little keyword makes a giant difference. Why? Because under these circumstances, TypeScript won’t compile anything. So we have the following cascade:

objects are untouched, but generate an implicit generalized shape declaration (interface)
enum will generate some boilerplate object-initializer along with a specialized shape declaration
const enum doesn’t generate anything beside a specialized shape declaration.

Now how is the latter then used in the code? By simple replacements. Consider this code:
enum Foo {
A = 1,
B = 2
}

const enum Bar {
A = 1,
B = 2
}

console.log(Bar.A, Foo.B);

Here we end up in JavaScript with the following outcome:
var Foo;
(function (Foo) {
Foo[Foo[“A"] = 1] = "A";
Foo[Foo["B"] = 2] = "B";
})(Foo || (Foo = {}));
console.log(1 /* A */, Foo.B);

Note that 5 lines alone have been generated for enum Foo, while enum Bar only resulted in a simple replacement (constant injection). Thus const enum is a compile-time only feature, while the original enum is a runtime + compile-time feature. Most projects will be well suited for const enum, but there may be cases where enum is preferred.
Continue reading %10 Essential TypeScript Tips and Tricks for Angular Devs%

Link: https://www.sitepoint.com/10-essential-typescript-tips-tricks-angular/

Using Angular Augury to Debug Your Code

Augury is an open-source tool allowing developers to profile and debug Angular 2 and 4 applications.
Modern web browsers provide developer consoles to inspect various elements on the page, which is really handy when trying to debug markup, styles, and scripts. However, this console isn’t enough to debug Angular applications that usually have lots of components, events, attributes, and a separate routing system.
Augury is a tool designed specifically for Angular apps. It’s an open-source debugging and profiling tool for Angular 2+ applications.
Augury is just a Chrome extension that’s quite simple to use, so you won’t need to spend hours and hours learning how to utilize this tool. We’re going to build a sample Angular app and then see Augury in action by exploring various parts of our project. So, let’s get started!
Hello, Augury!
Augury visualizes your app’s structure in a form of a tree, showing how components and their dependencies relate to each other. It also allows you to inspect properties of your objects and change them on the fly. On top of that, you can easily view the source code of a specific component, insert breakpoints as needed, work with events, and more. Lastly, you can browse the application’s routing system, as well as view the full list of all utilized modules.
Augury is only available as a Chrome extension (there’s no Firefox support yet, unfortunately) and installing it is as simple as going to this page and pressing the Install button. After that, you may open the developer tools by pressing Ctrl + Shift + I (Windows/Linux) or Cmd + Opt + I (macOS). You’ll note that a new tab called Augury has appeared. After switching to this tab, you’ll either see the application’s structure or the phrase “This application is not an Angular application”. I’ve noticed that sometimes it may be required to re-open the Developer Console in order for Augury to analyze the page properly, so watch out.
Now that we have Augury installed, let’s proceed to the next section and prepare the sample application that we’ll use as a playground!
Building a Sample App
In order to see Augury in action, we need something to debug, right? In this section, I’m going to quickly guide you through the process of creating a very simple application (loosely based on the sample app from the Angular’s official tutorial) listing some users and allowing you to edit them. Alternatively, you may grab the source code from my GitHub repo.
Before getting started, install Angular CLI on your machine if you don’t have it yet:
npm install -g @angular/cli

Next, create the skeleton of our new project:
ng new sitepoint-augury

Change the application’s title by tweaking the src/app/app.component.ts file:
// …

export class AppComponent {
title = ‘Augury Demo’;
}

Tweak the src/app/app.component.html by removing all the links to documentation added automatically by code generator and add an </app-users> line:
<div style=”text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>

<app-users></app-users>

Of course, we need a User component, so generate it now by running:
ng generate component users

Change the src/app/users/user.component.ts file in the following way:
import { Component, OnInit } from ‘@angular/core’;
import { User } from ‘./user.model’; // <— 1
import { UserService } from ‘./user.service’; // <— 2

@Component({
selector: ‘app-users’,
templateUrl: ‘./users.component.html’,
styleUrls: [‘./users.component.css’]
})
export class UsersComponent implements OnInit {
users: User[];

selectedUser: User;

onSelect(user: User): void { // <— 3
this.selectedUser = user;
}

constructor(private userService: UserService) { } // <— 4

ngOnInit() {
this.getUsers(); // <— 5
}

getUsers(): void { // <— 6
this.users = this.userService.getUsers();
}

}

Main things to note here:

We are importing a User model that will be created in a moment.
We’re also importing a UserService. It will simply return a list of hardcoded users, but let’s pretend they’re being fetched from some remote location.
We’re allowing the users to be selected by clicking on them. The currently selected user is stored in a separate selectedUser attribute.
Hook up the userService using the dependency injection mechanism.
Load the list of users once the component is initialized.
In order to get users, we’re utilizing our userService.

That’s pretty much it for this component.
Next, let’s create a model in a src/app/users/user.model.ts file. Each user is going to have an ID, a first and a last name:
export class User {
id: number;
first: string;
last: string;
}

Nothing complex.
Now let’s proceed to the UserService that’s going to be defined in the app/src/users/user.service.ts file:
import { Injectable } from ‘@angular/core’;
import { User } from ‘./user.model’;

@Injectable()
export class UserService {

constructor() { }

getUsers(): User[] {
return [
{
id: 1,
first: ‘John’,
last: ‘Doe’
},
{
id: 2,
first: ‘Margaret’,
last: ‘Brown’
}
]
}
}

The getUsers method simply returns an array of users with hardcoded data.
Now let’s display our users with the help of ngFor. Also, we’re going to add a click event listener and fire onSelect whenever a user is clicked on. When this happens, a form to edit the chosen user should be displayed (which is going to be done with the help of ngIf). Modify the src/app/users/user.component.html file like this:
<div *ngFor="let user of users" (click)="onSelect(user)"
[class.selected]="user === selectedUser">
<p>, (ID: )</p>
</div>

<div *ngIf="selectedUser">
<h3>Edit</h3>
<label for="first">First</label>
<input [(ngModel)]="selectedUser.first" placeholder="First name" id="first">

<label for="last">Last</label>
<input [(ngModel)]="selectedUser.last" placeholder="Last name" id="last">
</div>

We’re assigning a .selected CSS class to the chosen user, so let’s add some simple styling for it inside the src/app/users/user.component.css file:
.selected {
font-weight: bold;
}

Lastly, we have to import FormsModule and UserService inside the src/app/app.module.ts file:
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { FormsModule } from ‘@angular/forms’; // <—
import { UserService } from ‘./users/user.service’; // <—

import { AppComponent } from ‘./app.component’;
import { UsersComponent } from ‘./users/users.component’;

FormsModule should be listed in the imports section in the app.module.ts, whereas UserService goes to the providers:
@NgModule({
declarations: [
AppComponent,
UsersComponent
],
imports: [
BrowserModule,
FormsModule // <—
],
providers: [
UserService // <—
],
bootstrap: [AppComponent]
})

That’s it! Our sample application is finished, and you can open it by running the following command:
ng serve –open

Continue reading %Using Angular Augury to Debug Your Code%

Link: https://www.sitepoint.com/angular-augury-debug-code/

Boosting Your Workflow with Angular 5 Snippets and VS Code

In this article, we’ll focus on how to use Angular 5 snippets in Visual Studio Code to improve our workflow. We’ll first start with the basics of using and creating snippets. We’ll look at how we can use Angular snippets for VS Code in an Angular project. Then we’ll later look at how we can create our own snippets and share them with others.
For anyone who’s become proficient in a programming language, you know how boring it is to type the same code over and over again. You eventually start copying and pasting pieces of your code to spare your fingers the agony of writing another for loop.
What if your editor could help you insert this common code for you automatically as you type? That would be awesome, right?
Well, you probably know them as snippets. It’s a feature that’s common in every modern IDE currently available. Even Notepad++ supports them (though not enabled by default).
Prerequisites
Before you start, you’ll need to have the latest version of Visual Studio Code installed on your machine. We’ll also be looking at Angular 5 snippets. So having at least a basic knowledge of Angular will be helpful, but not necessary.
You’ll need to use an existing or new Angular 5 project in order to experiment with snippets. I assume you have the latest version of Node.js, or at least a version that’s not older than Node.js 6. Here’s the command for installing the Angular CLI tool if you haven’t:
npm install -g @angular/cli

# or
yarn global add @angular/cli

Snippets Explained
Snippets are templates that allow you to easily insert repetitive code. When you first install VSCode, it comes with snippets for JavaScript pre-installed. To check them out, just open an existing JavaScript file or create a new one in your workspace and try out typing these prefixes:

log
if
ifelse
forof
settimeout

As you type, a popup list will appear giving you options to autocomplete your code. As soon as the right snippet is highlighted, just press enter to insert the snippet. In some cases, such as log and for, you may need to press the down key to select the right snippet.
You’re probably wondering where these JavaScript snippets are coming from exactly. Well, you can find the exact definitions in these locations:

Windows – C:\Program Files\Microsoft VS Code\resources\app\extensions\javascript\snippets\javascript.json
Linux -/usr/share/code/resources/app/extensions/javascript/snippets/javascript.json

We’ll look into how we can create our own snippets, but first let’s explore some third-party snippets.
How to Use Snippets
At the time of writing, the Visual Studio Marketplace listed 934 extensions in the snippet category. You’ll find snippets for every programming language created, including Pascal! This means you probably should check out the marketplace before creating your own snippets. As mentioned earlier, we’ll be looking at Angular 5 snippets. Locate an existing Angular 5 project in your workspace or just create a new one:
ng new snippets-demo

Once the project is set up, open it in VSCode. Next, click the extension icon on the activity bar to open the Extensions panel. Search for Angular 5. The search results should list several Angular extensions. Install the one that has the author ‘John Papa’. After installation is done, click the reload button to restart VSCode. This Angular 5 snippets extension comes with over 50 snippets. About 70% of the snippets are written for TypeScript, and the rest are mostly for HTML. There are some Docker snippets in there too.

Let’s try a few of these Angular 5 snippets. Create a new file called app.service.ts inside the app folder. Open the file and start typing “a-service”. A pop-up list will appear as you type. Even before you finish typing, you should have the correct option highlighted. Press enter to insert the template. Once the snippet is entered, take note that the generated class name is highlighted for you to change.

Just type “App” and the entire class name will read “AppService”. Pretty convenient, right? Let’s try something different. Delete the entire code in app-service.ts and type this prefix:
a-service-httpclient

You should get a service class definition, including imports and HttpClient injection in the class constructor. Just like before, rename the class name to AppService.

Next, let’s use another snippet to define an HTTP GET request. Let’s define an empty GET method. For this piece of code, you have to type; don’t copy-paste:
getPosts(): Observable {

}

As you start to type “Observable”, a snippet option for it will appear. Just press enter and the Observable class will be imported for you automatically.

Next, let’s use another snippet to complete the function. Start typing this prefix: “a-httpclient-get”. Pressing enter will insert this snippet for you:
return this.httpClient.get(‘url’);

Change the URL to an imaginary path — let’s say /posts. Obviously our code won’t run, as we haven’t set up any APIs. Fix it by adding <any> after get. The complete method now looks like this.
getPosts(): Observable<any[]> {
return this.httpClient.get<any[]>(‘/posts’);
}

Now that we know a little bit about how to use Angular 5 snippets, let’s see how they’re created.
Continue reading %Boosting Your Workflow with Angular 5 Snippets and VS Code%

Link: https://www.sitepoint.com/boosting-workflow-angular-5-snippets-vs-code/

Top Angular Plugins for Sublime Text

This article covers a number of Angular plugins for the Sublime Text text editor.
Whether you’re new to Angular (version 2+) development, and looking to get started with it and integrate it more closely with your code editor of choice, or you’re an old hand at Angular development and you’re trying your hand with Sublime Text as a new editor, integrating the two has never been easier.
There are lots of options for Angular plugins that can smooth your way developing Angular apps using Sublime Text. You’ll need to set up the Sublime Text package manager (called “Package Control”) prior to getting started, and then you can take a look at the list of plugins here and see if any meet your needs!
Setting up Package Control
In order to use most of the Angular plugins that will be discussed in this article, you’ll first need to set up Package Control in Sublime Text. This is a fairly painless process. The easiest way involves copy-pasting a configuration code.

Use the hotkey CTRL + ` or use the View > Show Console menu to bring up the integrated Sublime Text console.
Paste the block of Python code into the console, which can be copied from the Package Control Installation page and follow the instructions there.
Once this is done, the Package Control menus will be set up! Now, all you’ll need to do is find and install your packages.

Installing a Sublime Text Package via Package Control Menus
Using Package Control is a breeze. You’ll need to open Package Control, select the install menu, and then choose and install a package:

Use the shortcut CMD + Shift + P (CTRL + Shift + P, depending on OS) to open the command palette.
Type install package and then press Enter, which brings you to the list of available packages.
Search for the package by name, select the package, then press Enter to install.

Angular 2 HTML Package
The Angular 2 HTML plugin provides augmented HTML syntax for Sublime Text. You’ll be able to use Angular attributes without syntax highlighting being broken. Additionally, the JavaScript parts of your pages will also highlight as JavaScript. A small but incredibly useful addition for Angular developers.
Angular 2 HTML Package Setup
At the time of this writing, this plugin was not present in Package Control, but can be installed manually via the following steps.

Close Sublime Text and navigate via the Command Line to your Sublime Text 3 “Packages” folder in your application installation. In macOS, this is at /Users/{user}/Library/Application Support/Sublime Text 3/Packages.

Clone the repository into your Packages folder with the following:
git clone https://github.com/princemaple/ngx-html-syntax

Re-open Sublime Text 3, and check in the View > Syntax menu to ensure that Ngx HTML is an option.

Additionally, you can have Sublime Text automatically highlight .component.html files with Angular 2 HTML Syntax:

Open a .component.html file.

Choose View > Syntax > Ngx HTML.

Go to Preferences > Settings > Syntax Specific. Because your current file is using the Ngx HTML syntax, it should open the syntax-specific settings file for Ngx HTML. If so, add an extensions entry to the settings panel on the right:
“extensions":
[
"component.html"
]

Restart Sublime Text. Now, all .component.html files should automatically use the Ngx Syntax plugin!

Continue reading %Top Angular Plugins for Sublime Text%

Link: https://www.sitepoint.com/top-angular-plugins-sublime-text/

Authenticating Firebase and Angular with Auth0: Part 2

This article was originally published on the Auth0.com blog, and is republished here with permission.
In this two-part tutorial series, we’ll learn how to build an application that secures a Node back end and an Angular front end with Auth0 authentication. Our server and app will also authenticate a Firebase Cloud Firestore database with custom tokens so that users can leave realtime comments in a secure manner after logging in with Auth0. The Angular application code can be found at the angular-firebase GitHub repo and the Node API can be found in the firebase-auth0-nodeserver repo.
The first part of our tutorial, Authenticating Firebase and Angular with Auth0: Part 1, covered:

intro and setup for Auth0 and Firebase
implementing a secure Node API that mints custom Firebase tokens and provides data for our app
Angular application architecture with modules and lazy loading
Angular authentication with Auth0 with service and route guard
shared Angular components and API service.

Authenticating Firebase and Angular with Auth0: Part 2
Part 2 of our tutorial will cover:

Displaying Dogs: Async and NgIfElse
Dog Details with Route Parameters
Comment Model Class
Firebase Cloud Firestore and Rules
Comments Component
Comment Form Component
Realtime Comments
Conclusion

Our completed app will look something like this:

Let’s pick up right where we left off at the end of Authenticating Firebase and Angular with Auth0: Part 1.
Displaying Dogs: Async and NgIfElse
Let’s implement the home page of our app — the dogs listing. We created the scaffolding for this component when we set up our Angular app’s architecture.
Important Note: Make sure your Node.js API is running. If you need a refresher on the API, refer to How to Authenticate Firebase and Angular with Auth0: Part 1 – Node API.
Dogs Component Class
Open the dogs.component.ts class file now and implement this code:
// src/app/dogs/dogs/dogs.component.ts
import { Component, OnInit } from ‘@angular/core’;
import { Title } from ‘@angular/platform-browser’;
import { ApiService } from ‘../../core/api.service’;
import { Dog } from ‘./../../core/dog’;
import { Observable } from ‘rxjs/Observable’;
import { tap, catchError } from ‘rxjs/operators’;

@Component({
selector: ‘app-dogs’,
templateUrl: ‘./dogs.component.html’
})
export class DogsComponent implements OnInit {
pageTitle = ‘Popular Dogs’;
dogsList$: Observable;
loading = true;
error: boolean;

constructor(
private title: Title,
private api: ApiService
) {
this.dogsList$ = api.getDogs$().pipe(
tap(val => this._onNext(val)),
catchError((err, caught) => this._onError(err, caught))
);
}

ngOnInit() {
this.title.setTitle(this.pageTitle);
}

private _onNext(val: Dog[]) {
this.loading = false;
}

private _onError(err, caught): Observable<any> {
this.loading = false;
this.error = true;
return Observable.throw(‘An error occurred fetching dogs data.’);
}

}

After our imports, we’ll set up some local properties:

pageTitle: to set our page’s <h1> and <title>
dogsList$: the observable returned by our API HTTP request to fetch the dogs listing data
loading: to show a loading icon while the API request is being made
error: to display an error if something goes wrong fetching data from the API.

We’re going to be using the declarative async pipe to respond to the dogsList$ observable returned by our API GET request. With the async pipe, we don’t need to subscribe or unsubscribe in our DogsComponent class: the subscription process will be managed automatically! We just need to set up our observable.
We’ll make Title and ApiService available to our class by passing them to the constructor, and then set up our dogsList$ observable. We’ll use RxJS operators tap (previously known as the do operator) and catchError to call handler functions. The tap operator executes side effects but does not affect the emitted data, so it’s ideal for setting other properties. The _onNext() function will set loading to false (since data has been successfully emitted). The _onError() function will set loading and error appropriately and throw an error. As mentioned before, we don’t need to subscribe or unsubscribe from the dogsList$ observable because the async pipe (which we’ll add in the template) will handle that for us.
On initialization of our component, we’ll use ngOnInit() to spy on the OnInit lifecycle hook to set the document <title>.
That’s it for our Dogs component class!
Dogs Component Template
Let’s move on to the template at dogs.component.html:
<!– src/app/dogs/dogs/dogs.component.html –>
<h1 class=”text-center">{{ pageTitle }}</h1>

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>
</ng-template>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">
<p class="lead">
These were the top <a href="http://www.akc.org/content/news/articles/the-labrador-retriever-wins-top-breed-for-the-26th-year-in-a-row/">10 most popular dog breeds in the United States in 2016</a>, ranked by the American Kennel Club (AKC).
</p>
<div class="row mb-3">
<div *ngFor="let dog of dogsList" class="col-xs-12 col-sm-6 col-md-4">
<div class="card my-2">
<img class="card-img-top" [src]="dog.image" [alt]="dog.breed">
<div class="card-body">
<h5 class="card-title">#{{ dog.rank }}: {{ dog.breed }}</h5>
<p class="text-right mb-0">
<a class="btn btn-primary" [routerLink]="[‘/dog’, dog.rank]">Learn more</a>
</p>
</div>
</div>
</div>
</div>
</div>

<app-comments></app-comments>

There are a couple things in this template that we’ll take a closer look at:

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>
</ng-template>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">

<div *ngFor="let dog of dogsList" …>

This code does some very useful things declaratively. Let’s explore.
First we have an <ng-template> element with a template reference variable (#noDogs). The <ng-template> element is never rendered directly. It’s intended to be used with structural directives (such as NgIf). In this case, we’ve created an embedded view with <ng-template #noDogs> which contains both the loading and error components. Each of these components will render based on a condition. The noDogs embedded view itself will not render unless instructed to.
So how (and when) do we tell this view to render?
The next <div *ngIf="… is actually an NgIfElse using the asterisk prefix as syntactic sugar. We’re also using the async pipe with our dogsList$ observable and setting a variable so we can reference the stream’s emitted values in our template (as dogsList). If something goes wrong with the dogsList$ observable, we have an else noDogs statement that tells the template to render the <ng-template #noDogs> view. This would be true before the data has been successfully fetched from the API, or if an error was thrown by the observable.
If dogsList$ | async has successfully emitted a value, the div will render and we can iterate over our dogsList value (which is expected to be an array of Dogs, as specified in our component class) using the NgForOf (*ngFor) structural directive to display each dog’s information.
As you can see in the remaining HTML, each dog will be displayed with a picture, rank, breed, and a link to their individual detail page, which we’ll create next.
View the Dogs component in the browser by navigating to your app’s homepage at http://localhost:4200. The Angular app should make a request to the API to fetch the list of dogs and display them!
Note: We’ve also included the <app-comments> component. Since we’ve generated this component but haven’t implemented its functionality yet, it should show up in the UI as text that says “Comments works!”
To test error handling, you can stop the API server (Ctrl+c in the server’s command prompt or terminal). Then try reloading the page. The error component should display since the API cannot be reached, and we should see the appropriate errors in the browser console:

Continue reading %Authenticating Firebase and Angular with Auth0: Part 2%

Link: https://www.sitepoint.com/authenticating-firebase-angular-auth0-2/

Creating UIs with Angular Material Design Components

In this tutorial, I’ll introduce you to Material Design in Angular, then we’ll look at how to create a simple Angular application with a UI built from various Angular Material components.
The widespread adoption of component-based frameworks such as Angular, React and Vue.js has seen a growing number of pre-built UI component collections become available. Using such collections can help developers to quickly create professional-looking applications.
What’s Material Design?
Material Design (codenamed Quantum Paper) is a visual language that can be used to create digital experiences. It’s a set of principles and guidelines across platforms and devices for interactivity, motion and components that simplify the design workflow for teams designing their product.
The Material components allow you to create professional UIs with powerful modularity, theming and customization features.
Introduction to Angular Material
Angular Material is the implementation of Material Design principles and guidelines for Angular. It contains various UI components, such as:

form controls (input, select, checkbox, date picker and sliders etc.),
navigation patterns (menus, sidenav and toolbar)
layout components (grids, cards, tabs and lists )
buttons
indicators (progress bars and spinners)
popups and modals
data tables with headers and pagination etc.

Requirements
Before you can continue with this tutorial, you need to make sure you have a development machine with Node (6.9.0+) and NPM (3+) installed.
You also need to have the Angular CLI installed. If that’s not the case, simply run the following command in your terminal or command prompt:
npm install -g @angular/cli

Create the Project with the Angular CLI
Let’s now create the Angular project using the Angular CLI. Simply run the following command:
ng new angularmaterialdemo

You can then serve your application by running:
cd angularmaterialdemo
ng serve

The application will be running at http://localhost:4200.
Since we’re going to demonstrate different Angular Material components, we need to create a few Angular components and routing configurations for a simple demo application, so go ahead and use the CLI to generate the components:
ng g component login
ng g component CustomerList
ng g component CustomerCreate

Next, open src/app/app.module.ts and add the router configuration:
/*…*/

import { RouterModule, Routes } from ‘@angular/router’;

/*…*/

const appRoutes: Routes = [
{ path: ‘customer-list’, component: CustomerListComponent },
{ path: ‘customer-create’, component: CustomerCreateComponent },
{
path: ‘login’,
component: LoginComponent
},
{ path: ”,

redirectTo: ‘/login’,

pathMatch: ‘full’

},
];

Getting Started with Angular Material
Now that we have a basic application, let’s get started by installing Angular Material and its different dependencies to enable the different features such as gestures and animations.
Installing Angular Material and Angular CDK
Let’s start by installing Angular Material and Angular CDK from npm.
Head back to your terminal and run the following command:
npm install –save @angular/material @angular/cdk

Adding HammerJS for Gestures Support
Components such as mat-slide-toggle, mat-slider and matTooltip require the HammerJS library for gestures support, so you need to install it for getting the full features of these components. Simply run the following command in your terminal:
npm install –save hammerjs

Next, open src/main.js (the entry point of your application) and import hammerjs
import ‘hammerjs’;

Adding a Theme
Angular Material has a bunch of pre-built themes. To use a theme, you simply need to import it in styles.css:
@import “~@angular/material/prebuilt-themes/indigo-pink.css";

You can find more information about theming in this guide.
Adding Angular Material Icons
Angular Material comes with a mat-icon component for icons, so you need to load the icon font before you can use it.
Add the following tag to your index.html file:

Using Animations with Angular Material Components
The last thing is enabling animations. Some components rely on the Angular animations module for advanced transitions, so you need to install the @angular/animations module and include the BrowserAnimationsModule in your application module configuration.
First, head back to your terminal and run the following command:
npm install –save @angular/animations

Next, open src/app/app.module.ts and add the following code:
/* … */
import {BrowserAnimationsModule} from ‘@angular/platform-browser/animations’;

@NgModule({
/*…*/
imports: [
BrowserModule,
BrowserAnimationsModule,
],
})
export class AppModule { }

Importing Angular Material Components
Before you can use any Angular Material component, you’ll have to import its module. Each component has its own module so you can include only the components you’re going to use.
Another approach is to create a separate module and import all the Angular Material components you need to use and then simply include this module in your application module.
So go ahead and create a src/app/material.module.ts file, and then add the following content:
import { NgModule } from ‘@angular/core’;
import {MatNativeDateModule,MatSnackBarModule,MatIconModule,MatDialogModule, MatButtonModule, MatTableModule, MatPaginatorModule , MatSortModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCard, MatCardModule, MatFormField, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule } from ‘@angular/material’;
import {MatDatepickerModule} from ‘@angular/material/datepicker’;
import {MatRadioModule} from ‘@angular/material/radio’;
import {MatSelectModule} from ‘@angular/material/select’;
import {MatSliderModule} from ‘@angular/material/slider’;
import {MatDividerModule} from ‘@angular/material/divider’;

@NgModule({
imports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule,MatTableModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCardModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],
exports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule, MatCheckboxModule, MatToolbarModule, MatCardModule,MatTableModule,MatTabsModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],

})

export class MyMaterialModule { }

Next, include this module in src/app/app.module.ts:
import { MyMaterialModule } from ‘./material.module’;

/*…*/

@NgModule({

/*…*/

imports: [

/*…*/
MyMaterialModule,
],
/*…*/
})

export class AppModule { }

That’s it: you can now use the imported Angular Material components in your Angular application.
Continue reading %Creating UIs with Angular Material Design Components%

Link: https://www.sitepoint.com/angular-material-design-components/