Powered by Blogger.

Angular Tutorial-Part 1

3 comments :

Angular Tutorial for Beginners – Complete Guide

Learn Angular step by step: setup, components, data binding, directives, services, routing, forms, HTTP and Signals – with ready-to-copy code examples.

✍️ By A143MK  •  ⏱️ 10 min read  •  🏷️ Angular, TypeScript, Web Development

1What is Angular?

Angular is a free, open-source front-end framework developed by Google for building fast, scalable single-page applications (SPAs). It uses TypeScript and gives you everything out of the box: components, routing, forms, HTTP client, testing tools and a powerful CLI.

FeatureBenefit
Component-basedReusable, testable UI blocks
TypeScriptStrong typing & better tooling
Dependency InjectionClean, maintainable services
Angular CLIGenerate, build, test with one command
SignalsFine-grained, fast reactivity

2Installation & Setup

Install Node.js (LTS version) first, then install the Angular CLI globally:

bash
npm install -g @angular/cli
ng version

# create a new project
ng new my-first-app
cd my-first-app
ng serve --open
💡 Tip: Your app will run at http://localhost:4200 and reloads automatically when you save a file.

Important project files:

  • src/main.ts – entry point that bootstraps the app
  • src/app/app.component.ts – root component
  • src/app/app.routes.ts – route definitions
  • angular.json – workspace/build configuration

3Components

A component = TypeScript class + HTML template + CSS styles. Generate one with the CLI:

bash
ng generate component hello
typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-hello',
  standalone: true,
  template: `<h2>Hello, {{ name }}!</h2>`,
  styles: [`h2 { color: #dd0031; }`]
})
export class HelloComponent {
  name = 'A143MK Readers';
}

Use it in any template: <app-hello></app-hello>

4Data Binding

Angular supports four types of data binding. Click the tabs:

html
<p>Welcome {{ userName }}</p>
html
<img [src]="imageUrl" [alt]="title">
<button [disabled]="isLoading">Save</button>
html
<button (click)="sayHello()">Click Me</button>
html
<!-- import FormsModule in the component -->
<input [(ngModel)]="userName">
<p>Hello {{ userName }}</p>
🧪 Live demo (two-way binding simulation):

Hello, Guest 👋

5Control Flow & Directives

Modern Angular (v17+) uses the built-in control flow syntax @if, @for and @switch:

html
@if (isLoggedIn) {
  <p>Welcome back!</p>
} @else {
  <button (click)="login()">Login</button>
}

<ul>
  @for (item of items; track item.id) {
    <li>{{ item.name }}</li>
  } @empty {
    <li>No items found</li>
  }
</ul>

Attribute directives change appearance or behaviour:

html
<div [class.active]="isActive" [style.color]="textColor">Styled text</div>
💡 Older syntax *ngIf and *ngFor still works, but the new control flow is faster and recommended.

6Parent ↔ Child Communication

typescript
import { Component, input, output } from '@angular/core';

@Component({
  selector: 'app-product',
  standalone: true,
  template: `
    <h3>{{ title() }}</h3>
    <button (click)="buy.emit(title())">Buy</button>
  `
})
export class ProductComponent {
  title = input.required<string>();   // data IN from parent
  buy = output<string>();            // event OUT to parent
}
html (parent)
<app-product [title]="'Laptop'" (buy)="onBuy($event)" />

7Services & Dependency Injection

Services hold shared logic and data. Angular injects them wherever needed.

typescript
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class TodoService {
  private todos: string[] = ['Learn Angular', 'Read A143MK blog'];

  getAll() { return this.todos; }
  add(todo: string) { this.todos.push(todo); }
}
typescript
import { Component, inject } from '@angular/core';
import { TodoService } from './todo.service';

@Component({ selector: 'app-todos', standalone: true, template: `...` })
export class TodosComponent {
  private todoService = inject(TodoService);
  todos = this.todoService.getAll();
}

8Routing

app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

export const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'user/:id', loadComponent: () =>
      import('./user/user.component').then(m => m.UserComponent) },
  { path: '**', redirectTo: '' }
];
html
<nav>
  <a routerLink="/" routerLinkActive="active">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet />
💡 loadComponent enables lazy loading – the code is downloaded only when the route is visited.

9Forms (Reactive Forms)

typescript
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <input formControlName="email" placeholder="Email">
      <input formControlName="password" type="password">
      <button [disabled]="form.invalid">Login</button>
    </form>
  `
})
export class LoginComponent {
  private fb = inject(FormBuilder);
  form = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]]
  });
  submit() { console.log(this.form.value); }
}

10HTTP Client (Calling APIs)

app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideHttpClient()]
};
typescript
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface Post { id: number; title: string; }

@Injectable({ providedIn: 'root' })
export class PostService {
  private http = inject(HttpClient);
  getPosts() {
    return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
  }
}

11Signals (Modern Reactivity)

typescript
import { Component, signal, computed, effect } from '@angular/core';

@Component({
  selector: 'app-counter',
  standalone: true,
  template: `
    <p>Count: {{ count() }} | Double: {{ double() }}</p>
    <button (click)="increment()">+1</button>
  `
})
export class CounterComponent {
  count = signal(0);
  double = computed(() => this.count() * 2);

  constructor() {
    effect(() => console.log('Count changed:', this.count()));
  }
  increment() { this.count.update(c => c + 1); }
}
🧪 Live demo (signal counter simulation):

Count: 0 | Double: 0

12Useful Angular CLI Commands

CommandPurpose
ng new app-nameCreate new project
ng serveRun dev server
ng g c nameGenerate component
ng g s nameGenerate service
ng buildProduction build (dist/ folder)
ng testRun unit tests
ng updateUpgrade Angular version
⚠️ Always keep Angular and Node.js versions compatible – check the official version compatibility guide.

13🎯 Quick Quiz – Test Yourself

🎉 Congratulations! You've learned the core concepts of Angular.
If this tutorial helped you, share it and leave a comment below. — A143MK

3 comments :

  1. https://react-bootstrap.netlify.app/docs/getting-started/introduction

    ReplyDelete
  2. https://react.dev/learn/creating-a-react-app

    ReplyDelete

Please Write a Message for Programming or something else 🙏