Alfie Mellor

Alfie Mellor

1559615603

Introduction to the Angular CLI

If you’re new to Angular or you’ve been developing in Angular for a while but only use Angular CLI to begin a new project, its time to get started using some of the features that can simplify your development process.

Why Use Angular CLI?

There are many ways you can architect Angular applications but for most developers, starting from a blank slate can be overwhelming and can often result in a project structure that turns into a support nightmare. Style guides and widely used conventions make code easier to read and maintain. Generating boilerplate code and a project structure with the Angular CLI is a great way to start your application.

Install Angular CLI

To install Angular CLI, you’ll need Node 8.x or higher and NPM 5.x or higher. You can check your versions by running node -v and npm -v in your terminal.

Introduction to the Angular CLI

To install the latest Angular CLI globally, run:

npm install -g

If you want to install it locally, you can install the it in a specific directory by dropping the -g flag:

npm install

If you already have the Angular CLI installed, you can check your version by running ng -v.

With the release of Angular 6, the CLI version number jumped from 1.7 to 6.0.0 to match and with the release of Angular 7 to 7.0.0. To check the latest version, visit: github.com/angular/angular-cli/releases

Introduction to the Angular CLI

ng new

The command we’ll use to create a new application in Angular CLI is ng new. To start a new demo application, we’ll use the command ng new demo-app. Let’s break down what’s going on in that command.

Introduction to the Angular CLIng is the CLI itself

Introduction to the Angular CLInew is the action we’re asking the CLI to perform

Introduction to the Angular CLIdemo-app is the name we’re giving our new application

By running this command, the CLI will generate a new application called demo-app and place all the files and subdirectories in a directory also called demo-app. We’re going to use this command but first, lets take a look at Angular CLI Flags.

Angular CLI Flags

Introduction to the Angular CLI

Flags are options that you can use for CLI actions. For example:

--dry-run

–dry-run is a flag that will show you what would be generated by your action command without actually creating any directories or files. Open up a terminal and run the following:

ng new demo-app --dry-run

Introduction to the Angular CLI

Angular CLI will show you all the directories and files that would be created by the command, along with that little reassurance at the bottom — “NOTE: Run with “dry run” no changes were made.

You can apply multiple flags to CLI actions, so lets give that a try. By default the directory created with ng new will be the same name as the application. But you can use the directory flag to name the new directory something different. Try it out with this command:

ng new demo-app --directory=./my-awesome-app --dry-run

Introduction to the Angular CLI

This time the dry run will show that all your files would be placed in the directory you specified with the –directory flag.

Our demo application is going to have more that one page, so we’re going to need routing. The default ng new doesn’t add routing so let’s run that last dry run again, but this time add the –routing flag.

ng new demo-app --directory=./my-awesome-app --routing --dry-run

Introduction to the Angular CLI

Now you’ll see that the app-rouitng.module.ts file has been added to the list of files that would be created.

To see a list of all the available flags for ng new run the –help flag:

ng new --help

Introduction to the Angular CLI

Notice that most of the flags have a single letter short cut you use. For example, instead of –dry-run just use -d. The long names all start with double dasheswhile the shortcuts start with just one.

Enough with the dry runs, lets create a new application

In your terminal, change into a directory where you want to place the demo application folder.

We’ll need routing for our demo app, so let’s use the –routing flag. We’ll also use the –skip-install flag on our action to see how it works. It will skip installing the dependency packages for the application.

–skip-install isa great option if you’re just wanting to test something quickly or get started on a new project offline or on a slow Internet connection. In your terminal run:

**ng new demo-app — routing — skip-install**

Now open the newly created application in your code editor. There are a lot of great code editors, but in this walkthrough, we’ll be using Visual Studio Code. Change into the new directory with:

cd demo-app

And launch VS Code with:

code .

Now in VS Code, open the package.json file and check out all those squiggly lines in the dependencies. If you hover over one, you’ll see a message that the npm dependency is not installed. That’s the result of the –skip-install flag we used on our cli command.

Introduction to the Angular CLI

Click on one of the squiggly underlined dependencies and then click the on the Lightbulb icon to see the Code Actions suggested by VS Code.

Introduction to the Angular CLI

Go ahead and choose the second choice run: npm install to install all the missing dependencies. It may take a minute or two for the installation to complete. That’s the couple of minutes you saved by using –skip-install.

ng serve

To view our demo application in the browser we‘ll go right back to the CLI. To start up a local server in memory and view the application, we can use the CLI command ng serve.

When it completes you’ll be able to view the app in your browser at port 4200. But let’s add the flag -o to our command and the CLI will also load the app in your browser when its ready.

ng serve -o

You should see the default page open in your browser.

Introduction to the Angular CLI

ng add

One of the commands added in Angular CLI 6 was ng add. It makes adding capabilities to your app easy and is a real time saver. Let’s use it to add Angular Material to apply some styling to our demo application.

In previous versions of the CLI, to install Angular Material you’d have to run:

npm install — save @angular/material
npm install — save @angular/animations

And then add the imports it into the /src/app/app.module.ts file, but no more! Let’s install Angular Material with ng add. Open another terminal window or the use the terminal in VS Code to run:

ng add @angular/material

That’s it. The CLI does all the heavy lifting and now Angular Material is installed and configured in your application.

Go check the demo application in your browser and you’ll see the font and spacing changes that Angular Material added to the page.

Introduction to the Angular CLI

ng generate

Now that we have Angular Material installed, let’s move on to a CLI command you’ll find incredibly helpful when developing in Angular.

ng generate will build out the schematic for many features you can add to your application. I find myself using it most often to create classes, components, modules, and services.

Let’s use it to add a few components to our demo application. We’ll create a component called first-page and ask ng generate to create it in a subdirectory called containers. In terminal run:

ng generate component containers/first-page

In VS Code you’ll see the containers subdirectory under src/app and under it, the first-page subdirectory with the boilerplate component files created by ng generate.

Introduction to the Angular CLI

Let’s add two more components to our application, but this time use the shortcuts by typing g instead of generate and c instead of component. In terminal run:

ng g c containers/second-page
ng g c containers/third-page

Now we have three boilerplate components ready to go in our app.

Introduction to the Angular CLI

Now that we have a few components, we need a way to get to them in our application. Let’s use ng generate to add a navigation menu. Since we already added Angular Material, we’ll use ng generate to add the menu using Angular Material. In terminal run:

ng g @angular/material

In VS Code, you can now see the myNav subdirectory and files that the CLI generated for the navigation menu.

Introduction to the Angular CLI

To add the Nav menu to our application, open the app.component.html file in VS Code. Delete all the boilerplate code in the file, replace it with

<app-my-nav></app-my-nav>

and save the file.

Now go to your browser and check out the new navigation menu.

Introduction to the Angular CLI

Navigation Menu

Notice that it’s responsive and gives you the “hamburger” menu when it gets down to mobile sizes.

Introduction to the Angular CLI

Navigation Menu at Mobile Size

That looks nice but if you try the menu links, it doesn’t do anything. Lets set it up to navigate between the three components we added earlier.

When we ran the CLI command to create a new application we used the –routing flag so it created our app.routing.module.ts file. Open it up in VS Code and inside the square brackets of our const routes, add:

{ path: ‘first-page’, component: FirstPageComponent }

Notice the red squiggly line under FirstPageComponent.

Introduction to the Angular CLI

Click on it and then click on the Light Bulb that pops up to see the Code Action that VS Code suggests. Then click on the suggested action and VS Code will add the import.

Introduction to the Angular CLI

We need to add two more paths for our second-page and third-page components, so lets use a keyboard shortcut in VS Code that will duplicate lines of code. Place your cursor on the line with the first-page path and press this key combo depending on your OS:

Windows: SHIFT + ALT + DOWN

Mac: SHIFT + OPTION + DOWN

Linux: SHIFT + CTRL + ALT + DOWN

Do it twice and then edit the new lines for the second-page and third-page components. Don’t forget to add commas to the ends of the first two lines, the duplicate short cut won’t do that for you.

{ path: 'first-page', component: FirstPageComponent },
{ path: 'second-page', component: SecondPageComponent },
{ path: 'third-page', component: ThirdPageComponent }

You can use the lightbulb code actions again to add the imports for the two additional route paths and save the file.

Now we can add routing to the our navigation menu. Open the my-nav.component.html file in the my-nav subdirectory.

In the code block, edit the the three boilerplate navigation items. Remove the HREF section and add the router link like this:

<a mat-list-item [routerLink]="['/first-page']" routerLinkActive="router-link-active">First Page</a>

You can delete the next two lines and then use the handy duplication trick again and edit the code for the second-page and third-page.

Introduction to the Angular CLI

Before we save the file, we need to add our router outlet. In the section where it says to Add Content add:

<router-outlet></router-outlet>

Introduction to the Angular CLI

Okay, save the file and go look at the application in the browser. You can now navigate between the three components using the navigation links.

Introduction to the Angular CLI

To get started using Angular CLI we:

  • used ng new to make a few dry runs and explore options with Flags
  • used ng new in the Angular CLI to create a new demo application
  • used ng serve to view our boilerplate app in the browser
  • added Angular Material with ng add
  • added three components with ng generate
  • added a navigation menu with ng generate
  • and edited our app.component.html and app.routing.module.ts files to use the navigation menu the CLI created

The simplicity and convenience of using Angular CLI made all these tasks faster and easier than using snippets or cutting and pasting from past projects. Take advantage of the tools you have and get started using Angular CLI in your application building.

#angular #javascript #web-development

What is GEEK

Buddha Community

Introduction to the Angular CLI
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

1593061105

Tutorial: Nx-style monorepo workspace with Angular CLI: Part 2

In Part 1 of this tutorial, we set up the booking desktop application project, a project for its end-to-end test suite, and the booking feature shell workspace library.

In this part, we’ll set up our custom generate project tool to automate the steps we did manually in Part 1. We’ll use it to create the shared and booking data acess libraries with NgRx Store, NgRx Effects, NgRx Schematics, and NgRx Store DevTools.

To configure the data access libraries while keeping the flow of dependencies correct, we’ll extract a shared environments library. Data access will be hooked up to the booking feature shell library.

#angular #angular-cli #angular-workspace #monorepo #nx #series-angular-architectural-patterns #ngrx

Roberta  Ward

Roberta Ward

1595337024

Tutorial: Nx-style monorepo workspace with Angular CLI: Part 3

In Part 3 of this tutorial, we create the passenger info and flight search feature libraries. We use the generate project tool to create the mobile booking application and its test project. Finally, we create a mobile version of the flight search component template.

This tutorial is part of the Angular Architectural Patterns series.

In Part 2 of this tutorial, we used the generate project tool to generate the booking data access and shared data access workspace libraries with NgRx Store and Effects. We extracted a shared environments library and hooked everything up to the booking feature shell library.

In this part of the tutorial, we’re going to create the passenger info and flight search feature libraries, each with a routed component. After that, we’ll create the mobile booking application project and its end-to-end test project. Finally, we’ll use builder file replacement to create a mobile version of the flight search component template.

THIS AD MAKES CONTENT FREE. HIDE

Passenger info feature library#

Let’s create our first feature library, the passenger info feature which is part of the booking domain.

npm run generate-project -- library feature feature-passenger-info --scope=booking --npm-scope=nrwl-airlines
# or
yarn generate-project library feature feature-passenger-info --scope=booking --npm-scope=nrwl-airlines
<>

Generate passenger info feature library.

After generating the project using the previous commands and parameters, we get this file and folder structure.

libs/booking/feature-passenger-info
├── src
│   ├── lib
│   │   ├── passenger-info
│   │   │   ├── passenger-info.component.css
│   │   │   ├── passenger-info.component.html
│   │   │   ├── passenger-info.component.spec.ts
│   │   │   └── passenger-info.component.ts
│   │   ├── booking-feature-passenger-info.module.spec.ts
│   │   └── booking-feature-passenger-info.module.ts
│   ├── index.ts
│   └── test.ts
├── README.md
├── karma.conf.js
├── tsconfig.lib.json
├── tsconfig.spec.json
└── tslint.json
<>

The file and folder structure of the booking passenger info feature library.

This looks a little different from a feature shell library and a data access library.

After the generate project tool has created the workspace library with an entry point Angular module, it runs the commands in the next listing.

The generate project tool also removed the --no-common-module flag from the ng generate module command we saw earlier, since this Angular module will be declaring components.

ng generate component passenger-info --project=booking-feature-passenger-info --module=booking-feature-passenger-info.module.ts --display-block
<>

Generate component command run when generating a feature library.

Let’s look at the Angular module our tool has generated.

// booking-feature-passenger-info.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

import {
  PassengerInfoComponent,
} from './passenger-info/passenger-info.component';

@NgModule({
  declarations: [PassengerInfoComponent],
  imports: [
    CommonModule,
  ],
})
export class BookingFeaturePassengerInfoModule {}
<>

Initial entry point Angular module in the passenger info feature library.

The entry point Angular module shown in the previous listing is a good starting point. We need to set up the feature routing for our component though. This is done in the next listing.

// booking-feature-passenger-info.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {
  PassengerInfoComponent,
} from './passenger-info/passenger-info.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    component: PassengerInfoComponent,
  },
];

@NgModule({
  declarations: [PassengerInfoComponent],
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
  ],
})
export class BookingFeaturePassengerInfoModule {}
<>

Passenger info feature Angular module with route configuration for its entry point component.

Nice! Now we’ve prepared our feature library to be hooked up to the feature shell library’s routing configuration.

The generated component is what you’d expect. What it’d display in a real booking application is not really important for the purpose of this article.

Let’s hook up this feature to the booking application’s routing by adding a route configuration to the booking feature shell Angular module as seen here.

#angular #angular-cli #angular-workspace #monorepo #nx #series-angular-architectural-patterns

Roberta  Ward

Roberta Ward

1595333359

Tutorial: Nx-style monorepo workspace with Angular CLI: Part 5

In the final part of this tutorial, we create the seatmap data access, seat listing feature, shared buttons UI, and shared formatting utilities library. Finally, we compare our approach with the full Nx toolchain.

This tutorial is part of the Angular Architectural Patterns series.

In Part 4 of this tutorial, we used our generate project tool to create the check-in data access library, the check-in feature shell library, the check-in desktop application, and the mobile check-in application. We hooked everything up and reviewed how much was automated by our tool.

In this part of the tutorial, we’re going to create the seatmap data access library with NgRx feature state. We then created the seat listing feature library and hooked it up to all applications with routing. Finally, we created the shared buttons UI library and the shared formatting utilities library which we used in the seat listing component.

THIS AD MAKES CONTENT FREE. HIDE

Seatmap data access library#

The shared seatmap feature has its own data access library. This is where we would add data services and application state management specific to the seatmap domain.

npm run generate-project -- library data-access --scope=seatmap --grouping-folder=shared/seatmap --npm-scope=nrwl-airlines --with-state
# or
yarn generate-project library data-access --scope=seatmap --grouping-folder=shared/seatmap --npm-scope=nrwl-airlines --with-state
<>

Generate the seatmap data access library.

For now, we’ll put the feature store and effects in place by using the --with-stateparameter of the generate project tool. Note that we use the nested grouping folder shared/seatmap.

// seatmap-data-access.module.ts
import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';

import { SeatmapEffects } from './+state/seatmap.effects';
import * as fromSeatmap from './+state/seatmap.reducer';

@NgModule({
  imports: [
    StoreModule.forFeature(fromSeatmap.seatmapFeatureKey, fromSeatmap.reducer),
    EffectsModule.forFeature([SeatmapEffects]),
  ],
})
export class SeatmapDataAccessModule {}
<>

The seatmap data access module.

The seatmap data access Angular module gives us an overview of what’s configured in the seatmap data access library. This is a good starting point.

ng run seatmap-data-access:lint

ng run seatmap-data-access:test --watch=false
<>

Lint and test the seatmap data access library.

Everything looks ready to go!

Seat listing feature library#

It’s time to add the first feature of the seatmap domain which is used in both the check-in and booking applications.

npm run generate-project -- library feature feature-seat-listing --scope=seatmap --grouping-folder=shared/seatmap --npm-scope=nrwl-airlines
# or
yarn generate-project library feature feature-seat-listing --scope=seatmap --grouping-folder=shared/seatmap --npm-scope=nrwl-airlines
<>

Generate the seatmap seat listing feature library.

Our tool generates an Angular module and a component for us.

To add this feature to our applications, we add a route to each feature shell module.

// check-in-feature-shell.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CheckInDataAccessModule } from '@nrwl-airlines/check-in/data-access';
import { SharedDataAccessModule } from '@nrwl-airlines/shared/data-access';

import { ShellComponent } from './shell/shell.component';

const routes: Routes = [
  {
    path: '',
    component: ShellComponent,
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'seatmap', // 👈
      },
      {
        path: 'seatmap', // 👈
        loadChildren: () =>
          import('@nrwl-airlines/seatmap/feature-seat-listing')
            .then(esModule => esModule.SeatmapFeatureSeatListingModule),
      },
    ],
  },
];

@NgModule({
  declarations: [ShellComponent],
  exports: [RouterModule],
  imports: [
    RouterModule.forRoot(routes),
    SharedDataAccessModule,
    CheckInDataAccessModule,
    CommonModule,
  ],
})
export class CheckInFeatureShellModule {}

#angular #angular-cli #angular-workspace #monorepo #nx #series-angular-architectural-patterns #ngrx

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