Angular Tutorial
Published: 2023-06-25 13:32:45

# Angular Tutorial

This tutorial will guide you through the basics of Angular, a popular JavaScript framework for building web applications. We'll cover various concepts and provide examples to help you understand and practice Angular development.

## Table of Contents
1. [Introduction](#introduction)
2. [Setup](#setup)
3. [Components](#components)
    - [Creating a Component](#creating-a-component)
    - [Using a Component](#using-a-component)
    - [Passing Data to a Component](#passing-data-to-a-component)
    - [Component Lifecycle Hooks](#component-lifecycle-hooks)
4. [Templates](#templates)
    - [Data Binding](#data-binding)
    - [Event Binding](#event-binding)
    - [Attribute Binding](#attribute-binding)
    - [Template Reference Variables](#template-reference-variables)
5. [Directives](#directives)
    - [ngIf Directive](#ngif-directive)
    - [ngFor Directive](#ngfor-directive)
    - [Custom Directives](#custom-directives)
6. [Services](#services)
    - [Creating a Service](#creating-a-service)
    - [Injecting a Service](#injecting-a-service)
7. [Routing](#routing)
    - [Setting up Routes](#setting-up-routes)
    - [Navigating Between Routes](#navigating-between-routes)
    - [Passing Parameters to Routes](#passing-parameters-to-routes)
8. [Forms](#forms)
    - [Template-Driven Forms](#template-driven-forms)
    - [Reactive Forms](#reactive-forms)
9. [HTTP Requests](#http-requests)
    - [Making GET Requests](#making-get-requests)
    - [Making POST Requests](#making-post-requests)
10. [Conclusion](#conclusion)

## 1. Introduction <a name="introduction"></a>
Angular is a powerful JavaScript framework developed by Google for building single-page applications. It follows the Model-View-Controller (MVC) architectural pattern and provides a rich set of features for developing dynamic web applications.

Some key features of Angular include:
- Two-way data binding
- Component-based architecture
- Dependency injection
- Templating and directives
- Routing and navigation
- Form handling
- HTTP requests

In this tutorial, we'll explore these features and learn how to use them effectively to build robust web applications.

## 2. Setup <a name="setup"></a>
Before getting started with Angular development, you need to set up your development environment. Follow these steps:

1. Install Node.js: Angular requires Node.js to run. Download and install Node.js from the official website: https://nodejs.org

2. Install Angular CLI: Angular CLI is a command-line interface tool that helps you create and manage Angular projects. Open your terminal or command prompt and run the following command to install Angular CLI globally:

   ```
   npm install -g @angular/cli
   ```

3. Create a new Angular project: Once Angular CLI is installed, you can create a new Angular project by running the following command:

   ```
   ng new my-angular-app
   ```

   This command will create a new directory named `my-angular-app` with a basic Angular project structure.

4. Change to the project directory: Use the following command to change to the project directory:

   ```
   cd my-angular-app
   ```

5. Start the development server: Finally, run the following command to start the development server and launch your Angular application:

   ```
   ng serve
   ```

   You should see a message indicating that the development server is running.

 Open your browser and visit `http://localhost:4200` to see your Angular application in action.

With these steps completed, you're ready to start building Angular applications!

## 3. Components <a name="components"></a>
Components are the building blocks of Angular applications. They represent different parts of the user interface and encapsulate their behavior and presentation logic. Let's explore how to create and use components in Angular.

### Creating a Component <a name="creating-a-component"></a>
To create a new component, use the Angular CLI command `ng generate component <component-name>`. This will create a new component file with the specified name and the necessary boilerplate code. For example, let's create a `hello-world` component:

```
ng generate component hello-world
```

This will create the following files:
- `hello-world.component.ts`: TypeScript code for the component.
- `hello-world.component.html`: HTML template for the component.
- `hello-world.component.css`: CSS styles specific to the component.
- `hello-world.component.spec.ts`: Unit tests for the component.

### Using a Component <a name="using-a-component"></a>
Once you've created a component, you can use it within other components or templates. To use a component, follow these steps:

1. Import the component: In the TypeScript file of the component where you want to use another component, import it at the top of the file. For example, to use the `hello-world` component, add the following import statement:

   ```typescript
   import { Component } from '@angular/core';
   import { HelloWorldComponent } from './hello-world.component';
   ```

2. Declare the component: Inside the `@Component` decorator of the component where you want to use another component, add the imported component to the `declarations` array. For example:

   ```typescript
   @Component({
     ...
     declarations: [HelloWorldComponent],
     ...
   })
   export class AppComponent {
     ...
   }
   ```

3. Use the component in the template: In the HTML template of the component, use the selector of the component as a custom HTML tag. For example, to use the `hello-world` component, add the following code to the template:

   ```html
   <hello-world></hello-world>
   ```

The `hello-world` component will now be rendered within the template of the parent component.

### Passing Data to a Component <a name="passing-data-to-a-component"></a>
Components can communicate with each other by passing data through input properties. Input properties allow a parent component to pass data to a child component. Let's see how to pass data from a parent component to a child component.

1. Define an input property: In the child component, add an `@Input` decorator to a property to indicate that it can receive data from the parent component. For example, in the `hello-world` component:

   ```typescript
   import { Component, Input } from '@angular/core';
   
   @Component({
     selector: 'hello-world',
     template: `
       <h2>{{ message }}</h2>
     `
   })
   export class HelloWorldComponent {
     @Input() message: string;
   }
   ```

2. Pass data to the child component: In the parent component's template, bind a value to the child component's input property using square brackets. For example, in the parent component's template:

   ```html
   <hello-world [message]="greeting"></hello-world>
   ```

   Here, `greeting` is a property of the parent component that holds the value you want to pass to the child component.

The child component will now receive the value of the `greeting` property

 from the parent component and display it in its template.

### Component Lifecycle Hooks <a name="component-lifecycle-hooks"></a>
Angular provides several lifecycle hooks that allow you to tap into different stages of a component's lifecycle. These hooks enable you to perform actions at specific moments, such as when a component is created, rendered, or destroyed. Here are some commonly used lifecycle hooks:

- `ngOnInit()`: Called after the component has been initialized and its input properties have been set.
- `ngOnChanges()`: Called whenever an input property of the component changes.
- `ngAfterViewInit()`: Called after the component's view and child views have been initialized.
- `ngOnDestroy()`: Called just before the component is destroyed and removed from the DOM.

You can implement these hooks by adding the corresponding methods to your component class. For example:

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `
    <h2>{{ message }}</h2>
  `
})
export class HelloWorldComponent implements OnInit, OnDestroy {
  @Input() message: string;

  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}
```

These hooks provide a way to perform additional logic or cleanup tasks at specific moments during a component's lifecycle.

That covers the basics of creating and using components in Angular. Now, let's move on to templates and learn how to bind data and handle events.

## 4. Templates <a name="templates"></a>
Templates are an essential part of Angular development. They define the structure and layout of your application's user interface. In this section, we'll explore different types of bindings and directives available in Angular templates.

### Data Binding <a name="data-binding"></a>
Data binding is a powerful feature of Angular that allows you to establish a connection between the component's data and the template. There are three types of data binding in Angular:

1. **Interpolation**: Interpolation allows you to display component data in the template by wrapping it in double curly braces (`{{ }}`). For example:

   ```html
   <h2>{{ title }}</h2>
   ```

   Here, `title` is a property of the component that will be displayed in the `<h2>` element.

2. **Property binding**: Property binding allows you to set an element's property value based on a component's property. It uses square brackets (`[]`) to bind a property to an expression. For example:

   ```html
   <img [src]="imageUrl" alt="Image">
   ```

   Here, `imageUrl` is a property of the component that holds the URL of an image. The `src` attribute of the `<img>` element will be bound to this property.

3. **Two-way binding**: Two-way binding enables synchronization of data between the component and the template. It uses the `[(ngModel)]` directive to bind a property to an input element and propagate changes in both directions. For example:

   ```html
   <input [(ngModel)]="username" type="text">
   ```

   Here, `username` is a property of the component that holds the value of an input field. Changes made in the input field will update the `username` property, and vice versa.

### Event Binding <a name="event-binding"></a>
Event binding allows you to respond to user actions, such as clicks, keyboard events, or form submissions. It uses parentheses (`()`) to bind an event to a component's method. For example:

```html
<button (click)="onButtonClick()">Click me</button>
```

Here, `onButtonClick()` is a

 method of the component that will be called when the button is clicked.

### Attribute Binding <a name="attribute-binding"></a>
Attribute binding allows you to set an element's attribute value based on a component's property. It uses square brackets (`[]`) similar to property binding but without binding to a property. For example:

```html
<button [disabled]="isDisabled">Submit</button>
```

Here, `isDisabled` is a property of the component that determines whether the button should be disabled. The `disabled` attribute of the `<button>` element will be bound to this property.

### Template Reference Variables <a name="template-reference-variables"></a>
Template reference variables allow you to refer to elements or Angular directives within a template. They are denoted by the hash symbol (`#`). For example:

```html
<input #nameInput type="text">
<button (click)="onSubmit(nameInput.value)">Submit</button>
```

Here, `nameInput` is a reference variable that refers to the `<input>` element. The `onSubmit()` method can access the value entered in the input field using `nameInput.value`.

That covers the basics of Angular templates and data binding. Next, let's explore directives in Angular.

## 5. Directives <a name="directives"></a>
Directives are instructions to modify the structure or behavior of HTML elements. Angular provides built-in directives, such as `ngIf` and `ngFor`, which are commonly used in templates. You can also create your own custom directives when needed. Let's explore these concepts.

### ngIf Directive <a name="ngif-directive"></a>
The `ngIf` directive allows you to conditionally render elements based on a condition. It evaluates the given expression and only renders the element if the expression is true. For example:

```html
<div *ngIf="showMessage">
  <p>Message is displayed.</p>
</div>
```

Here, `showMessage` is a property of the component that determines whether to display the message. If `showMessage` is true, the `<div>` element and its content will be rendered; otherwise, it will be removed from the DOM.

### ngFor Directive <a name="ngfor-directive"></a>
The `ngFor` directive allows you to iterate over a collection and generate HTML elements dynamically. It takes an iterable, such as an array, and repeats the element for each item in the collection. For example:

```html
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
```

Here, `items` is an array property of the component. The `<li>` element will be repeated for each item in the `items` array, and the `item` variable will hold the current item's value.

### Custom Directives <a name="custom-directives"></a>
You can create your own custom directives to extend the functionality of Angular templates. Custom directives allow you to encapsulate complex behavior and make it reusable across multiple components. Creating a custom directive involves two steps:

1. Define the directive: Create a TypeScript class and annotate it with the `@Directive` decorator. Implement the desired behavior within the class. For example:

   ```typescript
   import { Directive, ElementRef, HostListener } from '@angular/core';

   @Directive({
     selector: '[appCustomDirective]'
   })
   export class CustomDirective {
     constructor(private el: ElementRef) { }

     @HostListener('click') onClick() {
       this.highlight();
     }

     private highlight() {
       this.el.nativeElement.style.backgroundColor = 'yellow';
     }
   }
   ```

   This custom directive adds a click event listener to the element it is applied to and

 changes its background color to yellow when clicked.

2. Use the directive: Apply the custom directive to an element in a template using its selector. For example:

   ```html
   <button appCustomDirective>Click me</button>
   ```

   Here, the `appCustomDirective` directive is applied to the `<button>` element, and the defined behavior will be triggered when the button is clicked.

That covers the basics of directives in Angular. Now, let's move on to services, which are used to encapsulate and share data and functionality across different components.

## 6. Services <a name="services"></a>
Services in Angular are used to encapsulate common data and functionality that can be shared across multiple components. They allow you to keep your components lean and modular, while the services handle specific tasks. Let's explore how to create and use services in Angular.

### Creating a Service <a name="creating-a-service"></a>
To create a service, use the Angular CLI command `ng generate service <service-name>`. This will generate a new service file with the specified name and the necessary boilerplate code. For example, let's create a `data` service:

```
ng generate service data
```

This will create the following file:
- `data.service.ts`: TypeScript code for the service.

### Injecting a Service <a name="injecting-a-service"></a>
To use a service in a component, you need to inject it as a dependency. Angular provides a dependency injection system that manages the creation and sharing of instances of services. Follow these steps to inject a service into a component:

1. Import the service: In the TypeScript file of the component where you want to use the service, import it at the top of the file. For example, to use the `data` service:

   ```typescript
   import { Component } from '@angular/core';
   import { DataService } from './data.service';
   ```

2. Declare the service: Inside the `@Component` decorator of the component, add the imported service to the `providers` array. For example:

   ```typescript
   @Component({
     ...
     providers: [DataService],
     ...
   })
   export class AppComponent {
     ...
   }
   ```

3. Use the service: In the component's constructor, add a parameter of the service type and Angular will automatically inject an instance of the service. For example:

   ```typescript
   export class AppComponent {
     constructor(private dataService: DataService) {
       // You can access the service instance using 'this.dataService'
     }
   }
   ```

You can now use the service instance in the component's methods to access its properties and methods.

That covers the basics of creating and using services in Angular. Next, let's explore routing and navigation in Angular.

## 7. Routing <a name="routing"></a>
Routing allows you to navigate between different views or components in your Angular application. It enables you to define different routes and associate them with specific components. Let's explore how to set up routing in Angular.

### Setting up Routes <a name="setting-up-routes"></a>
To set up routes in your Angular application, follow these steps:

1. Import the necessary modules: In the main module file (`app.module.ts`), import the `RouterModule` and `Routes` from `@angular/router`. For example:

   ```typescript
   import { RouterModule, Routes } from '@angular/router';
   ```

2. Define your routes: Create an array of route configurations using the `Routes` type. Each route configuration consists of a path and the corresponding component. For example:

   ```typescript
   const routes: Routes = [
     { path: '', component: HomeComponent },
     {

 path: 'about', component: AboutComponent },
     { path: 'contact', component: ContactComponent },
   ];
   ```

   Here, `'home'`, `'about'`, and `'contact'` are the paths that will be associated with the `HomeComponent`, `AboutComponent`, and `ContactComponent`, respectively.

3. Add the RouterModule to the imports array: In the main module's `imports` array, add the `RouterModule.forRoot()` method, passing the defined routes as an argument. For example:

   ```typescript
   @NgModule({
     imports: [RouterModule.forRoot(routes)],
     ...
   })
   export class AppModule { }
   ```

   The `forRoot()` method is used when setting up the root level routing for the application.

4. Set up the router outlet: In the main component's template (`app.component.html`), add the `<router-outlet>` element. This element will act as a placeholder where the routed components will be displayed. For example:

   ```html
   <router-outlet></router-outlet>
   ```

### Navigating between Routes <a name="navigating-between-routes"></a>
To navigate between routes in your Angular application, you can use the `routerLink` directive or the `Router` service. Let's explore both approaches.

1. Using `routerLink`: In your template, use the `routerLink` directive to create links that navigate to different routes. For example:

   ```html
   <a routerLink="/">Home</a>
   <a routerLink="/about">About</a>
   <a routerLink="/contact">Contact</a>
   ```

   Here, clicking on the links will navigate to the corresponding routes.

2. Using `Router` service: In your component class, inject the `Router` service and use its methods to navigate programmatically. For example:

   ```typescript
   import { Router } from '@angular/router';

   export class MyComponent {
     constructor(private router: Router) { }

     goToAboutPage() {
       this.router.navigate(['/about']);
     }
   }
   ```

   Here, calling the `navigate()` method with the desired route path will navigate to that route.

That covers the basics of routing in Angular. You can now navigate between different views or components based on the defined routes.

## Conclusion <a name="conclusion"></a>
This tutorial provided an introduction to Angular, covering components, templates, data binding, event binding, directives, services, and routing. It included examples and explanations to help you get started with building Angular applications.

Remember, Angular is a vast framework with many more features and capabilities. As you progress in your Angular journey, you can explore advanced topics such as forms, HTTP communication, authentication, and more.

Keep learning, exploring, and building with Angular!