Angular: Creating new project
What is Angular CLI
- The Angular CLI helps us to quickly create an Angular application with all the configuration files and packages in one single command.
- It also helps us to add features (components, directives, services, etc) to existing Angular applications.
- The Angular CLI creates the Angular Application and uses:
- Typescript, Webpack ( for Module bundling),
- Karma ( for unit testing),
- Protractor ( for an end-to-end testing).
How to Create a new Angular project
Before starting with Angular, you need to set up your developer environment and install the required tools. Before going further install the following:
- Visual Studio Code (or any other editor of your choice)
- NPM Package Manager
Installing Angular CLI
The first step is to install the Angular CLI. We use the npm install command.
npm install -g @angular/cli@latest
The above command installs the latest version of Angular CLI on your machine. Note that we have used the -g flag, which stands for global, installs the Angular CLI system-wide so that you can use it in all your projects.
Finding the Angular CLI Version
You can find out the current installed Angular CLI version by using the command:
ng --version
Creating a new Angular Application
The creation of your first Angular project has become very simple using Angular CLI.
All you need to do is run the following command from the prompt:
ng new GettingStarted
Creating a new Angular Application
The above command will create a folder "GettingStarted" and copies all the required dependencies and configuration settings.
The Angular CLI performs the following tasks:
- Creates a new directory "GettingStarted".
- Sets up the folder structure for the application.
- Downloads and installs Angular libraries and any other dependencies.
- Installs and configures TypeScript.
- Installs and configures Karma & Protractor for testing.
This simplifies the initial setup process and allows you to focus on building your Angular application.
Running your new Angular Project
To run your application, all you need to do is type the following command:
ng serve
The above command compiles the Angular application and invokes the Webpack development server.
- The server keeps a watch on our project folder.
- If you make any changes in the code, it compiles the project again.
- You can also use
npm start
.
The Webpack Development server listens on HTTP Port 4200. Hence, open the browser and type http://localhost:4200/, and you will see "GettingStarted" app is running displayed on the browser.
Angular Project Folder Structure
Open the "GettingStarted" folder from Visual Studio Code, and you will see the following folder structure:
- Browse to the project folder in the command prompt.
- Type the following command to open the project in Visual Studio Code:
code .
This command opens the project in Visual Studio Code, allowing you to explore and work with the Angular project's folder structure.
Angular Project Folder Structure
Open the "GettingStarted" folder from Visual Studio Code, and you will see the following folder structure:
- The root folder "GettingStarted" contains subfolders:
- e2e
- node_modules
- src
- It also contains the following configuration files:
.editorconfig:
This is the configuration file for the Visual Studio Code editor..gitignore:
Git configuration to make sure autogenerated files are not committed to source control.angular.json:
This is the configuration file for Angular CLI.browserslist:
Ensures the compatibility of the Angular app with different browsers.karma.conf.js:
The Configuration file for the Karma test runner.package.json:
The package.json is an npm configuration file that lists the third-party packages that your project depends on. We also have package-lock.json.README.md:
The Readme file.- Typescript configuration files:
tsconfig.json:
The Typescript compiler configuration file specifying compiler options for the entire project.tsconfig.app.json:
Used for compiling the code.tsconfig.spec.json:
Used for compiling the tests.- TSLint configuration:
tslint.json:
TSLint is a static code analysis tool used to check Typescript code quality. It checks for readability, maintainability, and functionality errors.
Angular Project Folder Structure
Open the "GettingStarted" folder from Visual Studio Code, and you will see the following folder structure:
- The root folder "GettingStarted" contains subfolders:
e2e:
This folder contains the files required for end-to-end tests by Protractor. Protractor allows us to test our application against a real browser. You can learn more about Protractor here.node_modules:
All our external dependencies are downloaded and copied here by NPM Package Manager.src:
This is where our application lives.app folder:
The Angular CLI has created a simple application, which works out of the box. It creates:- The root component.
- A root module.
- A unit test class to test the component.
- The
src
folder is where our application lives.
The Component
The app.component.ts
is the component that is added to the project by Angular CLI. You will find it under the folder src/app
.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'GettingStarted';
}
The component class is the most important part of our application. It represents the view of the application, which is a region on the screen. It consists of three main parts:
- A class.
- A class decorator.
- An import statement.
Import Statement
import { Component } from '@angular/core';
The import statement is used to import the libraries that are used in our component class. This statement is similar to the C# using statement. Our component is decorated with the @Component
decorator, which is part of the @angular/core
module. Hence we need to refer to it in our class using the import method as shown above.
Component Class
export class AppComponent {
title = 'GettingStarted';
}
The component is a simple class defined using the export
keyword. Other parts of the app can import and use it. In the above component class, there is one property, title
, which is displayed when the application is run.
The component class can have many methods and properties. Its main purpose is to supply logic to our view.
@Component Decorator
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
The AppComponent
class is decorated with the @Component
decorator. The @Component
(called class decorator) provides metadata about our component. Angular uses this metadata to create the view.
The @Component
metadata above has three fields:
selector:
The selector tells Angular where to display the template. In the example above, the selector isapp-root
. Angular replaces this tag in the HTML file with the template (app.component.html
). Theapp-root
selector is used inindex.html
.templateUrl:
ThetemplateUrl
contains the path to the HTML template file. Angular uses this HTML file to render the view. In the example, it points to theapp.component.html
file.styleUrls:
ThestyleUrls
is an array of style sheets that Angular uses to style our HTML file. In the example, it points toapp.component.css
. Theapp.component.css
file is in the same folder as theAppComponent
. The file is empty, but you can create styles for the component and put them here.
Template
The app.component.html
is our template. The templateUrl
in the component class above points to this file. The app.component.html
file is in the same folder as the AppComponent
.
Root Module
Angular organizes the application code as Angular modules. Modules are closely related blocks of code in functionality. Every application must have at least one module. The module that loads first is the root module, our root module.
The root module is called app.module.ts
(under src/app
folder). It contains the following code:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The structure of the Angular module is similar to the component class. It consists of three parts:
- A class.
- A class decorator.
- An import statement.
Module Class
export class AppModule { }
Similar to the component, the Module class is defined with the export
keyword. Exporting the class ensures that you can use this module in other modules.
@NgModule Class Decorator
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
The Angular Modules require an @NgModule
decorator. The @NgModule
decorator passes the metadata about the module.
The @NgModule
metadata above has four fields:
declarations:
Declaration metadata lists the components, directives, and pipes that are part of this module.imports:
Imports metadata tells Angular the list of other modules used by this module. TheBrowserModule
is the core Angular module, containing critical services, directives, pipes, etc. TheAppRoutingModule
defines the application routes.providers:
Providers are the services that are part of this module, which can be used by other modules.bootstrap:
Bootstrap metadata identifies the root component of the module. When Angular loads theAppModule
, it looks for bootstrap metadata and loads all the components listed here. In this case, we want our module to loadAppComponent
, so we have listed it here.
Import Statements
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
The import statement is used to import the Angular libraries required by AppModule
, like NgModule
and BrowserModule
. We also need to import AppComponent
as we want to load it when we load AppModule
.
App Routing Module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The AppRoutingModule
in the file app-routing.module.ts
defines the routes of the application. These routes tell Angular how to move from one part of the application to another part or one view to another view.
The routes are defined in the constant const routes: Routes = [];
, which is currently empty. This module is defined as a separate module and is imported in AppModule
.
Bootstrapping Our Root Module
The app.component.html
is the file that we need to show to the user. It is bound to the AppComponent
component. We indicated that the AppComponent
is to be bootstrapped when AppModule
is loaded.
Now we need to ask Angular to load AppModule
when the application is loaded. This is done in the main.ts
file, found under the src
folder. The code is as follows:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
The second line of the import is the platformBrowserDynamic
library. This library contains all the functions required to bootstrap the Angular application.
We also import enableProdMode
from @angular/core
library. The Angular code by default runs in development mode. The development mode runs a few assertions and checks, which helps in debugging the application. enableProdMode
enables the production mode only if the current Angular environment is production.
The next import is our AppModule
.
The last import is the environment
, which is in the folder src/environments
. The file environment.ts
contains the contents for the current environment. The development environment uses the environment.ts
file. When you build the project for the production environment, then the environment.prod.ts
will be used. The environments are configured in angular.json
.
In the next line, our code checks the environmental variable and enables the production mode if the environment is production:
if (environment.production) {
enableProdMode();
}
Finally, the bootstrapModule
method of platformBrowserDynamic
library is used to bootstrap our AppModule
:
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
index.html
The selector app-root
, which we defined in our component metadata, is used as an HTML tag. Angular scans the HTML page, and when it finds the tag <app-root></app-root>
, it replaces the entire content with the content of app.component.html
.
Other Files & Folders
Assets
A folder where you can put images and anything else to be copied wholesale when you build your application.
Environments
The environments
folder is where we define environment variables for various build setups. The build setups can be:
- Development
- Production
- Testing
- Staging
Angular creates two build environments out of the box:
- Development (default)
- Production
The two files:
environment.ts
is the default for developmentenvironment.prod.ts
is for the production build.
polyfills.ts
Different browsers have different levels of support for web standards. Polyfills help normalize those differences.
styles.css
Your Angular global styles go here. Most of the time, you’ll want to have local styles in your components for easier maintenance, but styles that affect all of your apps need to be in a central place.
test.ts
This is the main entry point for your unit tests. It has some custom configuration that might be unfamiliar, but it’s not something you’ll need to edit.
Comments
Post a Comment