Angular 15 basic tutorial with examples

 

Angular 15 Basic Tutorial with Examples

Angular 15 is the latest version of the Angular framework that enables developers to build powerful, scalable, and maintainable web applications. In this tutorial, we will walk through the basic concepts of Angular 15, such as setting up an Angular application, creating components, working with templates, data binding, directives, services, and routing.

1. Setting Up an Angular Project

To get started with Angular 15, you need to install Node.js and Angular CLI. Follow the steps below:

Install Node.js and npm

Download and install Node.js from nodejs.org. This will also install npm (Node Package Manager), which is required to manage your project dependencies.

Install Angular CLI

The Angular CLI (Command Line Interface) is a tool to easily create Angular projects and run them in development mode.

To install Angular CLI globally, open your terminal or command prompt and run:

bash
npm install -g @angular/cli

Create a New Angular Application

Once the Angular CLI is installed, you can create a new Angular project using the following command:

bash
ng new angular-15-tutorial

You will be prompted to choose options for your project, such as whether to add Angular routing or choose a stylesheet format (CSS, SCSS, etc.). You can choose the default settings for now.

After the project is created, navigate to the project directory:

bash
cd angular-15-tutorial

Serve the Application

To start the development server and see your application in action, run:

bash
ng serve

This will start the app, and you can view it at http://localhost:4200 in your browser.


2. Angular Components

Components are the building blocks of Angular applications. Each component consists of:

  • HTML for the template.
  • CSS for styling.
  • TypeScript for logic.

Creating a Component

To generate a new component, run:

bash
ng generate component hello-world

This creates four files:

  • hello-world.component.ts (the TypeScript file for component logic)
  • hello-world.component.html (the template for the component)
  • hello-world.component.css (the style file for the component)
  • hello-world.component.spec.ts (for unit tests)

Basic Component Example

In hello-world.component.ts:

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message = 'Hello, Angular 15!'; }

In hello-world.component.html:

html
<h1>{{ message }}</h1>

In hello-world.component.css:

css
h1 { color: blue; }

Now, use the app-hello-world component in the app.component.html (the root component) by replacing the content with:

html
<app-hello-world></app-hello-world>

This will render "Hello, Angular 15!" in blue color when you run the application.


3. Data Binding in Angular

Angular provides several ways to bind data between components and templates.

1. Interpolation (Text Binding)

Used for binding component data to the template:

html
<h1>{{ message }}</h1>

2. Property Binding

Bind a property of an HTML element to a component property:

html
<img [src]="imageUrl" />

In the component:

typescript
export class HelloWorldComponent { imageUrl = 'https://angular.io/assets/images/logos/angular/angular.png'; }

3. Event Binding

Bind events (e.g., button clicks) to methods in the component:

html
<button (click)="changeMessage()">Change Message</button>

In the component:

typescript
export class HelloWorldComponent { message = 'Hello, Angular 15!'; changeMessage() { this.message = 'Message Changed!'; } }

4. Two-Way Binding

Angular provides ngModel for two-way data binding. For this, you need to import the FormsModule in the app.module.ts.

First, import FormsModule:

typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Import FormsModule here import { AppComponent } from './app.component'; import { HelloWorldComponent } from './hello-world/hello-world.component'; @NgModule({ declarations: [ AppComponent, HelloWorldComponent ], imports: [ BrowserModule, FormsModule // Add FormsModule to imports ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Then, in your component:

html
<input [(ngModel)]="message" /> <p>{{ message }}</p>

This will create an input box that updates the message property in real-time as the user types.


4. Directives in Angular

Directives are used to manipulate the DOM or bind data to DOM elements.

1. Structural Directives (e.g., *ngIf, *ngFor)

  • *ngIf: Conditionally include an element in the DOM.
html
<p *ngIf="isVisible">This paragraph is visible.</p>

In the component:

typescript
export class HelloWorldComponent { isVisible = true; }
  • *ngFor: Loop through a list and display each item.
html
<ul> <li *ngFor="let item of items">{{ item }}</li> </ul>

In the component:

typescript
export class HelloWorldComponent { items = ['Apple', 'Banana', 'Orange']; }

2. Attribute Directives (e.g., ngClass, ngStyle)

  • ngClass: Conditionally apply classes to elements.
html
<p [ngClass]="{ 'highlight': isHighlighted }">This is a text paragraph.</p>

In the component:

typescript
export class HelloWorldComponent { isHighlighted = true; }
  • ngStyle: Apply inline styles dynamically.
html
<p [ngStyle]="{ color: textColor }">Styled Text</p>

In the component:

typescript
export class HelloWorldComponent { textColor = 'red'; }

5. Services and Dependency Injection

Services in Angular are used to share data and logic across components. You can inject services into components using Angular's Dependency Injection (DI) system.

1. Creating a Service

To generate a service, use Angular CLI:

bash
ng generate service message

In the generated message.service.ts:

typescript
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MessageService { private message = 'Hello from the service!'; getMessage() { return this.message; } }

2. Injecting a Service into a Component

In the component, you can inject the service using the constructor:

typescript
import { Component, OnInit } from '@angular/core'; import { MessageService } from './message.service'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent implements OnInit { message: string; constructor(private messageService: MessageService) {} ngOnInit() { this.message = this.messageService.getMessage(); } }

In the template:

html
<p>{{ message }}</p>

6. Routing in Angular

Routing allows you to navigate between different views or pages in an Angular application.

1. Configuring Routes

In the app-routing.module.ts file, configure the routes:

typescript
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HelloWorldComponent } from './hello-world/hello-world.component'; const routes: Routes = [ { path: '', component: HelloWorldComponent }, { path: 'hello', component: HelloWorldComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

2. Adding RouterLink for Navigation

In the template, use routerLink to create links for navigation:

html
<nav> <a routerLink="/">Home</a> <a routerLink="/hello">Hello</a> </nav> <router-outlet></router-outlet>

The <router-outlet></router-outlet> is where the routed component will be displayed.


Conclusion

In this tutorial, we have covered the basics of Angular 15, including:

  1. Setting up a new Angular project.
  2. Creating and using components.
  3. Working with data binding (interpolation, property binding, event binding, and two-way binding).
  4. Using directives like *ngIf, *ngFor, ngClass, and ngStyle.
  5. Creating services and using dependency injection.
  6. Setting up routing to navigate between different views.

Angular 15 also comes with various improvements and features like enhanced type safety, better tree-shaking, and improved tooling, making it a great choice for building modern web applications.


Angular 15 New features

Comments

Popular posts from this blog

Top 200 telagu words in hindi daily life?

Building strong foundational knowledge in frontend development topics

Docker and Kubernetes Tutorials and QnA