Angular Tutorial

kiraaziz

kiraaziz

Posted on June 25, 2023

Angular Tutorial

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
  2. Setup
  3. Components
  4. Templates
  5. Directives
  6. Services
  7. Routing
  8. Forms
  9. HTTP Requests
  10. Conclusion

1. Introduction

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

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
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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

  1. Change to the project directory: Use the following command to change to the project directory:
   cd my-angular-app
Enter fullscreen mode Exit fullscreen mode
  1. Start the development server: Finally, run the following command to start the development server and launch your Angular application:
   ng serve
Enter fullscreen mode Exit fullscreen mode

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

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

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
Enter fullscreen mode Exit fullscreen mode

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

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:
   import { Component } from '@angular/core';
   import { HelloWorldComponent } from './hello-world.component';
Enter fullscreen mode Exit fullscreen mode
  1. 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:
   @Component({
     ...
     declarations: [HelloWorldComponent],
     ...
   })
   export class AppComponent {
     ...
   }
Enter fullscreen mode Exit fullscreen mode
  1. 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:
   <hello-world></hello-world>
Enter fullscreen mode Exit fullscreen mode

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

Passing Data to a Component

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:
   import { Component, Input } from '@angular/core';

   @Component({
     selector: 'hello-world',
     template: `
       <h2>{{ message }}</h2>
     `
   })
   export class HelloWorldComponent {
     @Input() message: string;
   }
Enter fullscreen mode Exit fullscreen mode
  1. 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:
   <hello-world [message]="greeting"></hello-world>
Enter fullscreen mode Exit fullscreen mode

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

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:

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');
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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:
   <h2>{{ title }}</h2>
Enter fullscreen mode Exit fullscreen mode

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

  1. 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:
   <img [src]="imageUrl" alt="Image">
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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:
   <input [(ngModel)]="username" type="text">
Enter fullscreen mode Exit fullscreen mode

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

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:

<button (click)="onButtonClick()">Click me</button>
Enter fullscreen mode Exit fullscreen mode

Here, onButtonClick() is a

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

Attribute Binding

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:

<button [disabled]="isDisabled">Submit</button>
Enter fullscreen mode Exit fullscreen mode

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

Template reference variables allow you to refer to elements or Angular directives within a template. They are denoted by the hash symbol (#). For example:

<input #nameInput type="text">
<button (click)="onSubmit(nameInput.value)">Submit</button>
Enter fullscreen mode Exit fullscreen mode

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

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

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:

<div *ngIf="showMessage">
  <p>Message is displayed.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

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

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:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

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

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:
   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';
     }
   }
Enter fullscreen mode Exit fullscreen mode

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

changes its background color to yellow when clicked.

  1. Use the directive: Apply the custom directive to an element in a template using its selector. For example:
   <button appCustomDirective>Click me</button>
Enter fullscreen mode Exit fullscreen mode

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

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

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
Enter fullscreen mode Exit fullscreen mode

This will create the following file:

  • data.service.ts: TypeScript code for the service.

Injecting a Service

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:
   import { Component } from '@angular/core';
   import { DataService } from './data.service';
Enter fullscreen mode Exit fullscreen mode
  1. Declare the service: Inside the @Component decorator of the component, add the imported service to the providers array. For example:
   @Component({
     ...
     providers: [DataService],
     ...
   })
   export class AppComponent {
     ...
   }
Enter fullscreen mode Exit fullscreen mode
  1. 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:
   export class AppComponent {
     constructor(private dataService: DataService) {
       // You can access the service instance using 'this.dataService'
     }
   }
Enter fullscreen mode Exit fullscreen mode

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

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

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:
   import { RouterModule, Routes } from '@angular/router';
Enter fullscreen mode Exit fullscreen mode
  1. 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:
   const routes: Routes = [
     { path: '', component: HomeComponent },
     {

 path: 'about', component: AboutComponent },
     { path: 'contact', component: ContactComponent },
   ];
Enter fullscreen mode Exit fullscreen mode

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

  1. 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:
   @NgModule({
     imports: [RouterModule.forRoot(routes)],
     ...
   })
   export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

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

  1. 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:
   <router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

Navigating between Routes

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:
   <a routerLink="/">Home</a>
   <a routerLink="/about">About</a>
   <a routerLink="/contact">Contact</a>
Enter fullscreen mode Exit fullscreen mode

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

  1. Using Router service: In your component class, inject the Router service and use its methods to navigate programmatically. For example:
   import { Router } from '@angular/router';

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

     goToAboutPage() {
       this.router.navigate(['/about']);
     }
   }
Enter fullscreen mode Exit fullscreen mode

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

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!

💖 💪 🙅 🚩
kiraaziz
kiraaziz

Posted on June 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related