Angular A-Z: How to Create and Complete a Basic Project
Angular is a TypeScript-based framework developed by Google, designed to create large-scale web applications. In this article, we will walk through the entire Angular process from A to Z, and create a simple project.
1. Installation
Install Node.js (if you donβt have it)
node -v
If you don't have it, download it from the official Node.js website.
Install Angular CLI
npm install -g @angular/cli
2. Basic Angular CLI Commands
Angular CLI (Command Line Interface) allows you to easily create, configure, and manage Angular projects. Here are the basic commands:
To create a new project
ng new project-name
This command will create a new Angular project and install necessary dependencies.
To run the project
ng serve
This will start the development server and make it accessible at http://localhost:4200.
To generate a component
ng generate component component-name
or shorthand:
ng g c component-name
To generate a service
ng generate service service-name
or shorthand:
ng g s service-name
To generate a module
ng generate module module-name
or shorthand:
ng g m module-name
To build the project
ng build
For production:
ng build --configuration production
3. Create a New Angular Application
ng new my-angular-app
- my-angular-app is your project name.
- When asked Would you like to add Angular routing?, select Yes.
- For Which stylesheet format would you like to use?, select either CSS or SCSS depending on your preference.
4. Navigate into the project folder and run it
cd my-angular-app
ng serve
This will open the application at http://localhost:4200.
5. Main Angular Components
π What is a Component?
A component is the basic building block of Angular, representing a specific part of the UI. It consists of three main files:
- .ts file for logic (TypeScript)
- .html file for the template (view)
- .css/.scss file for styling
To create a component, use:
ng generate component components/example
Example component code:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
message: string = 'Hello Angular';
}
π What is a Module?
Angular is built on modules (NgModule). Each module bundles components, services, and other resources together. The main module is AppModule.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
π What is a Service?
Services are used for data exchange, API requests, and general functionality.
To create a service, use:
ng generate service services/data
Example service code:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataService {
getData() {
return ['Data 1', 'Data 2', 'Data 3'];
}
}
6. Routing in Angular
Angular Router handles the navigation of pages within the application. To add routing, open app-routing.module.ts and add:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ExampleComponent } from './components/example/example.component';
const routes: Routes = [
{ path: 'example', component: ExampleComponent },
{ path: '', redirectTo: '/example', pathMatch: 'full' },
{ path: '**', component: ExampleComponent } // for 404 page
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
π Router Links
Use routerLink for navigation:
< a routerLink="/example">Go to Example Page</a>
π Dynamic Routing
If you need to pass data through a route:
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
To get the user ID:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const userId = this.route.snapshot.paramMap.get('id');
}
7. Virtual DOM in Angular
The Virtual DOM is an optimized version of the real DOM. It is created as an object model in JavaScript memory and is used to efficiently manage changes.
π How the Virtual DOM Works in Angular
- When Angular changes component data, it first creates a new version of the virtual DOM.
- Then it compares the new and old virtual DOMs, finding the differences.
- Only the differences are applied to the real DOM, reducing the number of changes and improving performance.
π Change Detection
Angular uses the Change Detection Mechanism to detect changes in data and update only the DOM elements that need to be updated.
π Ivy Rendering Engine
In recent versions, Angular uses the Ivy engine, which reduces bundle size and speeds up rendering by optimizing the virtual DOM.
You might wonder what decorators are. Now, let's talk about decorators and their usage in Angular.
8 Decorators - General Overview
Decorators are functions in TypeScript (and JavaScript) that are applied to classes, methods, properties, or parameters to add certain behavior. They are typically used on meta-code objects that do not change the value of data but rather add new functionalities or properties to them.
TypeScript, as a superset of JavaScript, implements a decorator system that also serves as a meta-code creation tool. Decorators are often used for classes but can also be applied to methods or parameters.
9 Decorators in Angular
Angular, as an advanced JavaScript/TypeScript framework, extensively uses decorators. They are a key feature of Angular and allow for easy interaction with various modules, components, services, and other structures. Even for Angular functionalities like Dependency Injection and configuration.
Two main reasons why Angular uses decorators:
- Code simplicity and clarity. Decorators allow you to write clean, short, and readable code by separating everything into specific attributes.
- Code modification and extension. Decorators provide quick modification and extension capabilities in Angular without requiring massive restructuring.
10 Examples of Using Decorators in Angular
@Component
This decorator is applied to a class to transform it into an Angular component. A component represents a part of the UI like text, images, or buttons. Example:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Injectable
This decorator is applied to a class that is used as a service. Services allow the code to perform specific functionality like API requests or business logic.
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private httpClient: HttpClient) {}
}
@NgModule
This decorator is applied to a class to define an Angular module, which is a container for components, services, and other configurations.
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
@Input
This decorator is used in the child component to pass property values from the parent component. Example:
@Component({
selector: 'app-child',
template: '< h2>{{childData}}< /h2>'
})
export class ChildComponent {
@Input() childData: string = '';
}
@Output
This decorator is used to send values from the child component. Example:
@Component({
selector: 'app-child',
template: `< button (click)="sendData()">Send Data < /button >`
})
export class ChildComponent {
@Output() dataSent = new EventEmitter();
sendData() {
this.dataSent.emit('Data from child');
}
}
Thus, you have learned basic information about Angular. For more examples, you can check out my GitHub.