Getting Started with Angular: Complete Guide
Samira Awad
Posted on August 19, 2024
Angular vs. AngularJS
It's important to distinguish between Angular and AngularJS. Although both are frameworks, they are completely different. AngularJS, the precursor to Angular, was innovative in its time, especially for single-page applications (SPA). One of its standout features was two-way data binding. However, AngularJS uses an older version of JavaScript.
With the formalization of ECMAScript and the adoption of TypeScript, which offers static typing, it became clear that a more robust framework was needed to develop stable applications. AngularJS had an architecture based on the MVC pattern, while Angular is based on a component-based configuration.
What is Angular? Introduction
Angular is the new framework designed to create single-page applications (SPA). When you create a new Angular project, you initially only have an index.html file, while the rest of the application's elements are organized into components. As the user navigates the application, Angular creates, updates, and destroys these components as needed.
In large applications, the initial load may be slow as all libraries, modules, components, and services must be loaded. However, Angular allows for the implementation of lazy loading, which optimizes the user experience by loading only the necessary components initially and loading the rest as the user navigates the application.
Angular is open-source and developed by Google. Its architecture completely separates the frontend from the backend, allowing both to be independent projects, making it easier for specialized teams to work on each area. On the backend, technologies like Node.js, .NET Core, Spring, and others can be used. Communication between frontend and backend is done via the HTTP protocol.
Angular is based on the MVC pattern and uses TypeScript, a superset of JavaScript created by Microsoft, which allows for the static typing of variables and functions. Although browsers only understand JavaScript, Angular transpiles TypeScript to JavaScript during the deployment process.
The framework is component-based, meaning it consists of reusable parts of the application. Components can interact with each other in various ways, allowing for the creation of robust and modular applications. With Angular CLI, you can generate the project skeleton and run commands like ng
, which allow you to create components, services, directives, perform tests, build the application, and more.
Angular is a complete framework, including libraries for routing management, HTTP requests, forms, testing, and more, without needing third-party libraries. Additionally, it is updated every six months with new versions that include improvements and bug fixes.
It is based on the RxJS library for reactive programming, which is fundamental in Angular. It is also compatible with other frameworks like Ionic and NativeScript, which allow for the creation of hybrid mobile applications. For SEO management, Angular offers Angular Universal.
Getting Started
Installation of NodeJS and Angular CLI
NodeJS Installation:
• The first step is to install NodeJS, which also includes the Node Package Manager (npm).Angular CLI Installation:
• Next, install the latest version of Angular CLI globally with the following command:
npm install -g @angular/cli
Code Editor:
• It is recommended to have a code editor like Visual Studio Code or any other of your choice.
Updating Angular CLI
• Since Angular is updated every six months, you need to uninstall the previous version with the following command:
npm uninstall -g @angular/cli
• Then, clear the cache with:
npm cache clean --force
• Finally, reinstall the latest version.
Creating a Project with Angular CLI
View available commands:
• You can see all the commands that Angular CLI offers with:
ng --version
Create the application skeleton:
• To create a new project, first, create a folder where the application will be hosted. Then, in the console, move inside that folder and create the project with:
ng new project-name
Project configuration:
• You will be asked if you want to use TypeScript's strict mode, to which you can answer "Yes."
• Select the type of stylesheet you want to use, for example, CSS.
• You will be asked if you want to enable Server-Side Rendering; you can decide according to your needs.
Running the Project
Command to start the server:
• Navigate inside the created project and use the following command:
ng serve
• This will create a development server that will run at http://localhost:4200/.Common error resolution:
• If you encounter the error of running the command outside the project, make sure you are inside the project folder.Transpilation and server:
• Angular will transpile the TypeScript code and generate a development server.Server control:
• To stop the server, use Ctrl + C and answer "Yes" when asked if you want to stop it.
Installing Third-Party Dependencies in Angular
Installing Bootstrap:
- Easy way:
• Go to the official website, access the "Get Started" section, copy the CSS URL, and paste it inside the header of the index.html file. Then, run the project again.
• To confirm that Bootstrap has loaded correctly, copy the code of any component from the Bootstrap page and paste it into the component's HTML. If it looks correct, the installation was successful.
- Recommended way:
• Go to the official Bootstrap website, access the "Download" section, and scroll down to find the npm installation option.
• Copy the installation command and paste it into your code editor's terminal. This will install Bootstrap and update the package.json and package-lock.json files, adding Bootstrap to the project's dependencies.
• Then, open the angular.json file and add the path to the Bootstrap styles file within the styles object:
"node_modules/bootstrap/dist/css/bootstrap.min.css"
• Make sure the path is correctly written and referenced.
Now, run the project again to apply the changes.
How to remove a dependency from the project:
• In your code editor's terminal, use the following command followed by the name of the library to uninstall (e.g., Bootstrap):
npm uninstall library-name
Installing an external library (example with ngx-toastr):
Installing ngx-toastr:
• Copy the installation command from the official ngx-toastr page and paste it into your code editor's terminal. You will see it added to the package.json and package-lock.json files.
• Then, in the angular.json file, within the scripts object, import the ngx-toastr style from node_modules. The import can be copied directly from the official page in the "Styles" section.
• Import the necessary modules in app.module.ts and configure them according to the official documentation. The modules should be within imports.
• Inject the Toastr service into your component's constructor using dependency injection.
Angular Project Structure
- src folder: This is the most important folder in the project and consists of three main sections:
• app: Components, modules, and services. By default, one component and one module are created.
A component consists of several files:
• css: for styles.
• html: for the component structure.
• spec.ts: for unit testing.
• ts: for the component logic.The root module (app.module.ts) includes the components within the declarations section, other modules in imports, and services in providers.
In bootstrap, only the root module is placed, which indicates which component is the starting point of the application.
• assets: Static files (e.g., images).
• environments: Environment configurations (e.g., environment variables).
The src folder also contains the index.html file, which follows the SPA (Single Page Application) approach. Within this file, you will find the root component identified as app-root.
Within the components, you will find the root component's .ts file, where the app-root selector is defined. This selector indicates that you want to render that component in the single index.html page.
The HTML code for this component is located in the corresponding .html file. You can empty the content of this file and write whatever you want. When you open the browser, you will see what you have placed in this file.
_Note:
If you don't see the module and instead see a config file, it's because Angular 17, by default, creates a project that uses the new standalone API. You can change this configuration by setting the option to false when creating the project, using the following command:
ng new project-name --routing --standalone false
- Other Files and Folders:
- e2e: End-to-end automated tests.
- node_modules: Project dependencies.
- environments: Environment variables for production, development, and testing.
- main.ts: The application entry point. By default, it starts with the AppModule created by default.
- polyfills.ts: A file used for compatibility with older browsers.
- styles.css: A global styles file that will impact all components of the application.
- test.ts: A file used for testing.
- Additional Files:
- .browserslistrc: Compatibility settings for browsers.
- angular.json: Angular configuration file.
- package.json: Application and dependency configuration. All dependencies with an @ prefix are Angular-specific, and those without are third-party dependencies. It also includes development dependencies, which will only be used during development, such as TypeScript, Angular CLI, testing tools, and others.
- package-lock.json: A file used to record the versions of the packages we are using.
- README.md: An information file about the application.
- .gitignore: A file containing all the files and folders we want to ignore when committing. This way, other developers won't download these folders when cloning the project.
Data Binding in Angular
DataBinding is one of the most important features provided by Angular, allowing us to communicate or synchronize data between the component and the DOM. The DOM would be the component's HTML file, and the component would be the corresponding TypeScript (TS) file.
Types of DataBinding:
- Interpolation: Allows sending unidirectional data from the component to the DOM using the syntax
{{value}}
.
Property Binding: It's better to use it when manipulating the properties of HTML elements, allowing unidirectional data to be sent from the component to the DOM using the syntax
[property]="value"
.Event Binding: Data travels from the DOM to the component when an event occurs, using the syntax
(event)="method()"
.Two-Way Binding: Bidirectional communication, meaning data flows in both directions between the component and the DOM using
[(ngModel)]="value"
. The value is updated in real-time both in the HTML and in the component.
Configuration: To use ngModel, we must import FormsModule in app.module.ts:
import { FormsModule } from '@angular/forms'; imports: [ FormsModule, ... ]
Examples:
• Interpolation:
<h3>Hello, my name is {{person.name}} and my last name is {{person.lastName}}</h3>
{{ getSuma(20,25) }} <!-- Returns the result of the TS method (sum value: 45) -->
• Property Binding:
<img [src]="imageUrl" alt="Image">
<h3 [style.color]="color">Colored Text</h3>
Disable a button based on a TS variable: disabled = true;
:
<button [disabled]="disabled" class="btn btn-outline-danger">Radio 2</button>
• Event Binding:
<button (click)="increment(1)">Increment</button>
In TS, the method is defined:
increment(number1: number) { this.number += number1; }
• Two-Way Binding:
<input [(ngModel)]="number" placeholder="Enter a value">
Application: The value of the number is updated in real-time both in the HTML and in the component.
Deploying the Application
When deploying to production, Angular will only consider the src folder. The other folders and files are only used during development.
-
Build for Production:
• To optimize the application for production, run:
ng build --prod
• This will generate a dist folder that contains the application ready to be deployed.
Deployment (example with Netlify):
• Create an account on Netlify and upload the files from the dist folder.
• Netlify will provide a link to share the application.
• Note: When you build the application, Angular will insert the different scripts, and as you navigate the application, Angular will dynamically create, update, and destroy components through the routing system.
Final Structure of an Angular Project
Configuration Files:
• .editorconfig, .gitignore, karma.config.js, tsconfig.json.src Folder:
• app: Components, modules, and services.
• assets: Static files (e.g., images).
• environments: Environment configurations (e.g., environment variables).node_modules Folder: Project dependencies.
e2e Folder: End-to-end tests.
With this guide, you should be prepared to start working with Angular and efficiently manage projects.
Posted on August 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.