Tuesday, March 11, 2025

#11 @Output

 

Understanding @Output() in Angular 19

The @Output() decorator in Angular 19 is used to send data from a child component to a parent component. It allows child components to emit events, which the parent component can listen to and respond to.


Step-by-Step Guide with Example

We will create a simple Angular 19 project where a child component emits an event, and the parent component listens for it.


Step 1: Create a New Angular 19 Project

Ensure you have Angular CLI installed:

npm install -g @angular/cli@latest

Now, create a new Angular project:

ng new angular-output-demo
cd angular-output-demo
ng serve

Step 2: Generate a Child Component

Create a new child component that will emit an event to the parent:

ng generate component components/child

This creates:

  • child.component.ts
  • child.component.html
  • child.component.scss

Step 3: Implement @Output() in the Child Component

Modify child.component.ts:

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent {
  // Define an EventEmitter to send data to the parent
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from Child Component!');
  }
}

Step 4: Update the Child Component Template

Modify child.component.html:

<div class="child-container">
  <h3>Child Component</h3>
  <button (click)="sendMessage()">Send Message to Parent</button>
</div>

Step 5: Listen for Events in the Parent Component

Modify app.component.ts to receive the event:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  receivedMessage: string = '';

  // Method to handle event from child
  onMessageReceived(message: string) {
    this.receivedMessage = message;
  }
}

Step 6: Update the Parent Component Template

Modify app.component.html:

<h2>Parent Component</h2>
<p><strong>Message from Child:</strong> {{ receivedMessage }}</p>

<!-- Pass event listener to the child -->
<app-child (messageEvent)="onMessageReceived($event)"></app-child>

Step 7: Add Some Styling (Optional)

Modify child.component.scss:

.child-container {
  border: 2px solid #007bff;
  padding: 15px;
  margin: 10px;
  border-radius: 8px;
  text-align: center;
  background-color: #f0f8ff;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 5px;
}

button:hover {
  background-color: #0056b3;
}

Step 8: Run the Project

Start the Angular application:

ng serve

Open the browser at http://localhost:4200, click the "Send Message to Parent" button, and see the message update in the parent component.


Key Takeaways

βœ… @Output() allows child components to send data to parent components.
βœ… EventEmitter<T> is used to emit events with a specific data type.
βœ… The parent listens for the emitted event using event binding:

<app-child (messageEvent)="onMessageReceived($event)"></app-child>

Would you like to modify this example to pass more complex data like objects or arrays? πŸš€

#10 @Input()

 

Understanding @Input() in Angular 19

The @Input() decorator in Angular 19 allows a child component to receive data from a parent component. It is commonly used to pass dynamic values, making components reusable and modular.


Step-by-Step Guide with Example

We will create a simple Angular 19 project where a parent component passes data to a child component using @Input().


Step 1: Create a New Angular 19 Project

Make sure you have the latest Angular CLI installed:

npm install -g @angular/cli@latest

Now, create a new Angular project:

ng new angular-input-demo
cd angular-input-demo
ng serve

Step 2: Generate a Child Component

Create a new child component that will receive data using @Input():

ng generate component components/user-card

This creates:

  • user-card.component.ts
  • user-card.component.html
  • user-card.component.scss
  • user-card.component.spec.ts

Step 3: Define @Input() in the Child Component

Modify user-card.component.ts to accept input from the parent:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.component.html',
  styleUrls: ['./user-card.component.scss']
})
export class UserCardComponent {
  // Define inputs to receive data from the parent component
  @Input() name: string = 'Guest';
  @Input() age: number = 0;
  @Input() city: string = 'Unknown';
}

Step 4: Update the Child Component Template

Modify user-card.component.html:

<div class="user-card">
  <h3>User Information</h3>
  <p><strong>Name:</strong> {{ name }}</p>
  <p><strong>Age:</strong> {{ age }}</p>
  <p><strong>City:</strong> {{ city }}</p>
</div>

Step 5: Use <app-user-card> in the Parent Component

Modify app.component.html:

<h2>Passing Data to Child Component</h2>

<app-user-card name="Alice" age="28" city="New York"></app-user-card>
<app-user-card name="Bob" age="35" city="Los Angeles"></app-user-card>
<app-user-card name="Charlie" age="22" city="Chicago"></app-user-card>

Step 6: Add Some Styling (Optional)

Modify user-card.component.scss:

.user-card {
  border: 1px solid #ccc;
  padding: 15px;
  margin: 10px;
  border-radius: 8px;
  text-align: left;
  background-color: #f9f9f9;
}

Step 7: Run the Project

Start the Angular application:

ng serve

Open your browser at http://localhost:4200, and you should see the user information passed from the parent component to the child component.


Key Takeaways

βœ… @Input() allows parent components to pass data to child components.
βœ… Child components use @Input() to declare properties that accept values.
βœ… Parent components bind values to @Input() properties like:

<app-user-card name="Alice"></app-user-card>

Would you like to extend this example with real dynamic data from an API or a list of users? πŸš€

#9 Signals

 

Understanding Angular 19 Signals

In Angular 19, signals are a reactivity model introduced to improve performance, simplify state management, and provide fine-grained change detection without relying on RxJS. Signals help track state changes efficiently and work seamlessly with Angular’s rendering system.

Key Features of Signals

  1. Declarative State Management - Makes state tracking more predictable.
  2. Automatic Dependency Tracking - Updates components when signal values change.
  3. Optimized Rendering - Reduces unnecessary component re-renders.
  4. Better Performance - No need for manual ChangeDetectionStrategy.OnPush.

Step-by-Step Angular 19 Signals Example

We will create a basic Angular 19 application where we use signals to manage a counter.


Step 1: Create a New Angular 19 Project

Ensure you have Angular CLI 19 installed. If not, update it:

npm install -g @angular/cli@latest

Now, create a new Angular project:

ng new angular-signals-demo
cd angular-signals-demo

Select SCSS or any other styling option based on your preference.


Step 2: Install Required Dependencies

Angular Signals are built-in, so you don’t need additional packages.

Just ensure your project is running:

ng serve

Step 3: Create a Counter Service using Signals

Generate a service to manage our counter state using signals.

ng generate service services/counter

Now, modify counter.service.ts:

import { Injectable, signal } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  // Define a signal with an initial value of 0
  count = signal(0);

  // Method to increment the count
  increment() {
    this.count.set(this.count() + 1);
  }

  // Method to decrement the count
  decrement() {
    this.count.set(this.count() - 1);
  }

  // Method to reset the count
  reset() {
    this.count.set(0);
  }
}

Step 4: Use Signals in a Component

Generate a new component to display and update the counter.

ng generate component components/counter

Now, update counter.component.ts:

import { Component } from '@angular/core';
import { CounterService } from 'src/app/services/counter.service';

@Component({
  selector: 'app-counter',
  templateUrl: './counter.component.html',
  styleUrls: ['./counter.component.scss'],
})
export class CounterComponent {
  constructor(public counterService: CounterService) {}

  // Methods to modify the count
  increment() {
    this.counterService.increment();
  }

  decrement() {
    this.counterService.decrement();
  }

  reset() {
    this.counterService.reset();
  }
}

Step 5: Update the Counter Component HTML

Modify counter.component.html:

<div class="counter-container">
  <h2>Counter with Angular 19 Signals</h2>
  <p>Current Count: {{ counterService.count() }}</p>

  <button (click)="increment()">+</button>
  <button (click)="decrement()">-</button>
  <button (click)="reset()">Reset</button>
</div>

Step 6: Add Counter Component to App Component

Modify app.component.html to include the counter:

<h1>Welcome to Angular 19 Signals Demo</h1>
<app-counter></app-counter>

Step 7: Style the Counter (Optional)

Modify counter.component.scss:

.counter-container {
  text-align: center;
  margin-top: 20px;

  h2 {
    font-size: 1.5rem;
    margin-bottom: 10px;
  }

  p {
    font-size: 1.2rem;
    font-weight: bold;
  }

  button {
    font-size: 1rem;
    margin: 5px;
    padding: 10px 15px;
    cursor: pointer;
    border: none;
    background-color: #007bff;
    color: white;
    border-radius: 5px;
  }

  button:hover {
    background-color: #0056b3;
  }

  button:nth-child(2) {
    background-color: #dc3545;
  }

  button:nth-child(2):hover {
    background-color: #c82333;
  }

  button:nth-child(3) {
    background-color: #6c757d;
  }

  button:nth-child(3):hover {
    background-color: #5a6268;
  }
}

Step 8: Run the Project

Start the Angular application:

ng serve

Open the browser at http://localhost:4200 and see your signal-powered counter in action!


Key Takeaways

  • signal(value) creates a reactive state variable.
  • .set(newValue) updates the signal’s value.
  • .update(fn) modifies the value based on the current state.
  • Signals are synchronous and automatically notify the UI of changes.

This example demonstrates how easy it is to use signals in Angular 19 for state management. Would you like to extend this with more features like async operations or effects? πŸš€


#8.4 CRUD- SQL Lite (WIP.....)

Angular [<19] CRUD application to store data in SQLite instead of localStorage, follow these steps:


πŸ›  Steps to Implement SQLite in Angular

  1. Set up an SQLite database using an API (Node.js + Express + SQLite3).
  2. Modify the Angular service to perform CRUD operations using HTTP requests.
  3. Update the component to call the service instead of using localStorage.

πŸ“Œ Step 1: Set Up SQLite API (Node.js + Express + SQLite3)

We'll create an Express API that interacts with SQLite.

1️⃣ Install Dependencies

Run this in your backend folder:

npm init -y
npm install express sqlite3 cors body-parser

2️⃣ Create server.js (Express API)

const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(cors());
app.use(bodyParser.json());

// Connect to SQLite
const db = new sqlite3.Database('./employees.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
    if (err) console.error(err.message);
    console.log('Connected to SQLite database.');
});

// Create Employee Table
db.run(`CREATE TABLE IF NOT EXISTS employees (
    empid INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    contactNo TEXT,
    emailId TEXT,
    city TEXT,
    state TEXT,
    pinCode TEXT,
    address TEXT
)`);

// Get all employees
app.get('/employees', (req, res) => {
    db.all('SELECT * FROM employees', [], (err, rows) => {
        if (err) return res.status(500).json({ error: err.message });
        res.json(rows);
    });
});

// Add a new employee
app.post('/employees', (req, res) => {
    const { name, contactNo, emailId, city, state, pinCode, address } = req.body;
    db.run(`INSERT INTO employees (name, contactNo, emailId, city, state, pinCode, address) VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [name, contactNo, emailId, city, state, pinCode, address],
        function (err) {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ empid: this.lastID });
        }
    );
});

// Update an employee
app.put('/employees/:id', (req, res) => {
    const { name, contactNo, emailId, city, state, pinCode, address } = req.body;
    const { id } = req.params;
    db.run(`UPDATE employees SET name=?, contactNo=?, emailId=?, city=?, state=?, pinCode=?, address=? WHERE empid=?`,
        [name, contactNo, emailId, city, state, pinCode, address, id],
        function (err) {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ updated: this.changes });
        }
    );
});

// Delete an employee
app.delete('/employees/:id', (req, res) => {
    const { id } = req.params;
    db.run('DELETE FROM employees WHERE empid = ?', [id], function (err) {
        if (err) return res.status(500).json({ error: err.message });
        res.json({ deleted: this.changes });
    });
});

// Start server
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

Run the API:

node server.js

πŸ“Œ Step 2: Modify Angular Service (employee.service.ts)

We will replace localStorage with HTTP API calls.

Create employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Employee {
  empid?: number;
  name: string;
  contactNo: string;
  emailId: string;
  city: string;
  state: string;
  pinCode: string;
  address: string;
}

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private apiUrl = 'http://localhost:3000/employees';

  constructor(private http: HttpClient) {}

  getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.apiUrl);
  }

  addEmployee(employee: Employee): Observable<any> {
    return this.http.post(this.apiUrl, employee);
  }

  updateEmployee(employee: Employee): Observable<any> {
    return this.http.put(`${this.apiUrl}/${employee.empid}`, employee);
  }

  deleteEmployee(empid: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${empid}`);
  }
}

πŸ“Œ Step 3: Modify app.component.ts

Replace Local Data with API Calls

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EmployeeService, Employee } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  employeeForm: FormGroup;
  employeeList: Employee[] = [];
  selectedEmployee: Employee | null = null;

  constructor(private employeeService: EmployeeService) {
    this.createForm();
  }

  ngOnInit() {
    this.loadEmployees();
  }

  createForm() {
    this.employeeForm = new FormGroup({
      empid: new FormControl(null),
      name: new FormControl('', [Validators.required]),
      contactNo: new FormControl(''),
      emailId: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      pinCode: new FormControl('', [Validators.required, Validators.minLength(6)]),
      address: new FormControl('')
    });
  }

  loadEmployees() {
    this.employeeService.getEmployees().subscribe(data => {
      this.employeeList = data;
    });
  }

  onSave() {
    if (this.selectedEmployee) {
      this.employeeService.updateEmployee(this.employeeForm.value).subscribe(() => {
        this.loadEmployees();
        this.reset();
      });
    } else {
      this.employeeService.addEmployee(this.employeeForm.value).subscribe(() => {
        this.loadEmployees();
        this.reset();
      });
    }
  }

  onEdit(employee: Employee) {
    this.selectedEmployee = employee;
    this.employeeForm.patchValue(employee);
  }

  onDelete(empid: number) {
    if (confirm("Are you sure you want to delete?")) {
      this.employeeService.deleteEmployee(empid).subscribe(() => {
        this.loadEmployees();
      });
    }
  }

  reset() {
    this.employeeForm.reset();
    this.selectedEmployee = null;
  }
}

πŸ“Œ Step 4: Update app.module.ts

Ensure you import HttpClientModule.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

🎯 Final Steps

  1. Start the SQLite API
    node server.js
    
  2. Run Angular App
    ng serve
    
  3. Test CRUD operations in the UI πŸŽ‰

πŸš€ What We Changed

βœ… Replaced localStorage with an SQLite database
βœ… Created a Node.js API with SQLite for CRUD operations
βœ… Updated Angular to use HTTP services


This setup provides a real database instead of localStorage, making the app persistent and scalable. Let me know if you need more modifications! πŸš€πŸ”₯


====================================================================


Since you're using Angular 19, the core structure remains the same, but there are some minor updates in best practices, TypeScript versions, and RxJS changes. I'll provide the updated Angular 19 implementation with SQLite using a Node.js backend.


πŸ›  Steps to Implement SQLite with Angular 19

  1. Set up an SQLite database with an API (Node.js + Express + SQLite3).
  2. Modify Angular Service using HttpClient to perform CRUD operations.
  3. Update the Component and Forms using the latest Angular 19 best practices.
  4. Ensure compatibility with RxJS changes (tap(), subscribe() syntax, etc.).

πŸ“Œ Step 1: Set Up SQLite API (Node.js + Express + SQLite3)

1️⃣ Install Dependencies

Run the following command inside the backend folder:

npm init -y
npm install express sqlite3 cors body-parser dotenv

2️⃣ Create server.js (Express API)

require('dotenv').config();
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;

app.use(cors());
app.use(bodyParser.json());

// Connect to SQLite
const db = new sqlite3.Database('./employees.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
    if (err) console.error(err.message);
    console.log('Connected to SQLite database.');
});

// Create Employee Table
db.run(`CREATE TABLE IF NOT EXISTS employees (
    empid INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    contactNo TEXT NOT NULL,
    emailId TEXT NOT NULL,
    city TEXT,
    state TEXT,
    pinCode TEXT,
    address TEXT
)`);

// Get all employees
app.get('/employees', (req, res) => {
    db.all('SELECT * FROM employees', [], (err, rows) => {
        if (err) return res.status(500).json({ error: err.message });
        res.json(rows);
    });
});

// Add a new employee
app.post('/employees', (req, res) => {
    const { name, contactNo, emailId, city, state, pinCode, address } = req.body;
    db.run(`INSERT INTO employees (name, contactNo, emailId, city, state, pinCode, address) VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [name, contactNo, emailId, city, state, pinCode, address],
        function (err) {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ empid: this.lastID });
        }
    );
});

// Update an employee
app.put('/employees/:id', (req, res) => {
    const { name, contactNo, emailId, city, state, pinCode, address } = req.body;
    const { id } = req.params;
    db.run(`UPDATE employees SET name=?, contactNo=?, emailId=?, city=?, state=?, pinCode=?, address=? WHERE empid=?`,
        [name, contactNo, emailId, city, state, pinCode, address, id],
        function (err) {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ updated: this.changes });
        }
    );
});

// Delete an employee
app.delete('/employees/:id', (req, res) => {
    const { id } = req.params;
    db.run('DELETE FROM employees WHERE empid = ?', [id], function (err) {
        if (err) return res.status(500).json({ error: err.message });
        res.json({ deleted: this.changes });
    });
});

// Start server
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

Run the API

node server.js

πŸ“Œ Step 2: Modify Angular Service (employee.service.ts)

We will replace localStorage with HTTP API calls.

Create employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Employee {
  empid?: number;
  name: string;
  contactNo: string;
  emailId: string;
  city: string;
  state: string;
  pinCode: string;
  address: string;
}

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private apiUrl = 'http://localhost:3000/employees';

  constructor(private http: HttpClient) {}

  getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.apiUrl);
  }

  addEmployee(employee: Employee): Observable<any> {
    return this.http.post(this.apiUrl, employee);
  }

  updateEmployee(employee: Employee): Observable<any> {
    return this.http.put(`${this.apiUrl}/${employee.empid}`, employee);
  }

  deleteEmployee(empid: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${empid}`);
  }
}

πŸ“Œ Step 3: Modify app.component.ts

Replace Local Data with API Calls

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EmployeeService, Employee } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  employeeForm!: FormGroup;
  employeeList: Employee[] = [];
  selectedEmployee: Employee | null = null;

  constructor(private employeeService: EmployeeService) {}

  ngOnInit() {
    this.createForm();
    this.loadEmployees();
  }

  createForm() {
    this.employeeForm = new FormGroup({
      empid: new FormControl(null),
      name: new FormControl('', [Validators.required]),
      contactNo: new FormControl('', Validators.required),
      emailId: new FormControl('', Validators.required),
      city: new FormControl(''),
      state: new FormControl(''),
      pinCode: new FormControl('', [Validators.required, Validators.minLength(6)]),
      address: new FormControl('')
    });
  }

  loadEmployees() {
    this.employeeService.getEmployees().subscribe(data => {
      this.employeeList = data;
    });
  }

  onSave() {
    if (this.selectedEmployee) {
      this.employeeService.updateEmployee(this.employeeForm.value).subscribe(() => {
        this.loadEmployees();
        this.reset();
      });
    } else {
      this.employeeService.addEmployee(this.employeeForm.value).subscribe(() => {
        this.loadEmployees();
        this.reset();
      });
    }
  }

  onEdit(employee: Employee) {
    this.selectedEmployee = employee;
    this.employeeForm.patchValue(employee);
  }

  onDelete(empid: number) {
    if (confirm("Are you sure you want to delete?")) {
      this.employeeService.deleteEmployee(empid).subscribe(() => {
        this.loadEmployees();
      });
    }
  }

  reset() {
    this.employeeForm.reset();
    this.selectedEmployee = null;
  }
}

πŸ“Œ Step 4: Update app.module.ts

Ensure you import HttpClientModule.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

🎯 Final Steps

  1. Start the SQLite API
    node server.js
    
  2. Run Angular App
    ng serve
    
  3. Test CRUD operations in the UI πŸŽ‰

πŸš€ What We Updated for Angular 19

βœ… Removed any in TypeScript
βœ… Ensured strict types for RxJS (tap(), subscribe())
βœ… Used ! operator to avoid null issues
βœ… Modernized form validation


Now your Angular 19 app works with SQLite via Node.js! πŸŽ―πŸš€ Let me know if you need any changes. πŸ”₯

# 8.3 SQLite Hands-on with Python

 

SQLite Shenanigans: The Funniest Database Adventure Ever

Welcome to the World of SQLite!

Ah, SQLite. The database that doesn't need a server, yet still has the audacity to demand our attention! Today, we embark on a hilarious yet educational journey into the land of SQL wizardry, where databases exist in .db files and SQL statements are our spells.

So, buckle up and get ready to dive into the wonderful (and sometimes frustrating) world of SQLite with Python!


Ex 1: Opening a Database – The "Hello World" of SQLite

Before we can do anything, we need to open a database. It’s like saying "hi" before you ask for a favor.

import sqlite3

try:
    with sqlite3.connect("my.db") as conn:
        print(f"Opened SQLite database with version {sqlite3.sqlite_version} successfully.")
except sqlite3.OperationalError as e:
    print("Failed to open database:", e)

If all goes well, SQLite gives us a nod of approval. If not, well, expect an error message that makes you question your life choices.


Ex 2: Creating Tables – Because We Need a Place to Put Stuff

We can’t just throw our data into the void. We need tables! Here’s how we create them:

import sqlite3

sql_statements = [
    """CREATE TABLE IF NOT EXISTS projects (
            id INTEGER PRIMARY KEY,
            name text NOT NULL,
            begin_date DATE,
            end_date DATE
        );""",

    """CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            priority INT,
            project_id INT NOT NULL,
            status_id INT NOT NULL,
            begin_date DATE NOT NULL,
            end_date DATE NOT NULL,
            FOREIGN KEY (project_id) REFERENCES projects (id)
        );"""
]

try:
    with sqlite3.connect('my.db') as conn:
        cursor = conn.cursor()
        for statement in sql_statements:
            cursor.execute(statement)
        conn.commit()
        print("Tables created successfully.")
except sqlite3.OperationalError as e:
    print("Failed to create tables:", e)

And just like that, we have tables! SQLite doesn’t complainβ€”yet.


Ex 3: Inserting Records – Filling Our Database with Meaningful Chaos

Creating tables is nice, but they’re just empty shells without data. Let's add some records!

import sqlite3

def add_project(conn, project):
    sql = ''' INSERT INTO projects(name,begin_date,end_date)
              VALUES(?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, project)
    conn.commit()
    return cur.lastrowid

def add_task(conn, task):
    sql = '''INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date)
             VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, task)
    conn.commit()
    return cur.lastrowid

def main():
    try:
        with sqlite3.connect('my.db') as conn:
            project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30')
            project_id = add_project(conn, project)
            print(f'Created a project with the id {project_id}')
            tasks = [
                ('Analyze the requirements of the app', 1, 1, project_id, '2015-01-01', '2015-01-02'),
                ('Confirm with user about the top requirements', 1, 1, project_id, '2015-01-03', '2015-01-05')
            ]
            for task in tasks:
                task_id = add_task(conn, task)
                print(f'Created task with the id {task_id}')
    except sqlite3.Error as e:
        print(e)

if __name__ == '__main__':
    main()

Now our database has some actual data! It’s alive! 🀯


Ex 4: Updating Data – Because Plans Always Change

First, let's change a single column, because why not?

import sqlite3

sql = 'UPDATE tasks SET priority = ? WHERE id = ?'

try:
    with sqlite3.connect('my.db') as conn:
        cursor = conn.cursor()
        cursor.execute(sql, (2,1))
        conn.commit()
except sqlite3.OperationalError as e:
    print(e)

Now, let's go crazy and update multiple columns!

import sqlite3

sql = 'UPDATE tasks SET end_date = ?'

try:
    with sqlite3.connect('my.db') as conn:
        cursor = conn.cursor()
        cursor.execute(sql, ('2015-02-03',))
        conn.commit()
except sqlite3.Error as e:
    print(e)

Change is good, right?


Ex 5 & 6: Querying the Database – Let’s See What We Did

To check if we actually did things right, let's retrieve some data:

import sqlite3

try:
    with sqlite3.connect('my.db') as conn:
        cur = conn.cursor()
        cur.execute('select id, name, priority from tasks')
        rows = cur.fetchall()
        for row in rows:
            print(row)
except sqlite3.OperationalError as e:
    print(e)

Want a specific record? Say no more!

import sqlite3

try:
    with sqlite3.connect('my.db') as conn:
        cur = conn.cursor()
        cur.execute('SELECT id, name, priority FROM tasks WHERE id =?', (1,))
        row = cur.fetchone()
        if row:
            print(row)
except sqlite3.OperationalError as e:
    print(e)

Ex 7: Reusable Code – The Lazy Programmer’s Dream

We love functions. They do things so we don’t have to.

import sqlite3

def get_task_by_id(id: int) -> tuple:
    try:
        with sqlite3.connect('my.db') as conn:
            cur = conn.cursor()
            cur.execute('select id, name, priority from tasks where id =?', (id,))
            row = cur.fetchone()
            return row, None
    except sqlite3.OperationalError as e:
        return None, e      

if __name__ == '__main__':
    task, error = get_task_by_id(1)
    if error is not None:
        print(f'Error: {error}')
    else:
        print(task)

And that’s a wrap! πŸŽ‰ You now have the power to create, update, and retrieve data like a true SQLite ninja. Use it wisely (or recklessly, your call). Happy coding! πŸ˜†

Monday, March 10, 2025

#8.2 SqLite CRUD - Advanced Topics

 Here’s an SQLite tutorial expansion covering Joins, Indexing, and Transactions in four short modules (~30 minutes total). This will help students optimize queries, combine data from multiple tables, and ensure data integrity.


🎯 Goal of the Tutorial

  • Understand Joins to combine multiple tables.
  • Learn Indexing for faster queries.
  • Use Transactions to maintain database integrity.

πŸ“Œ Module 1: Understanding Joins (8 mins)

πŸ”Ή Why Use Joins?

Joins help combine data from multiple tables using common keys.

πŸ”Ή Creating Example Tables

Students Table

CREATE TABLE students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    course_id INTEGER
);

Courses Table

CREATE TABLE courses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    course_name TEXT NOT NULL
);

Inserting Data

INSERT INTO courses (course_name) VALUES ('Computer Science'), ('Mathematics');
INSERT INTO students (name, course_id) VALUES ('Alice', 1), ('Bob', 2);

πŸ”Ή Performing Joins

INNER JOIN (Most Common)

SELECT students.name, courses.course_name
FROM students
JOIN courses ON students.course_id = courses.id;

βœ”οΈ Shows only students with a matching course.

LEFT JOIN (All Students, Even Without a Course)

SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses ON students.course_id = courses.id;

βœ”οΈ Includes students without a course (NULL values).

RIGHT JOIN (Not Supported in SQLite)

SQLite doesn’t support RIGHT JOIN, but we can swap table positions and use LEFT JOIN.

πŸ›  Exercise 1

  1. Create a teachers table.
  2. Use a JOIN to show which teacher is assigned to which course.

πŸ“Œ Module 2: Indexing for Performance (7 mins)

πŸ”Ή What is Indexing?

  • Speeds up queries by reducing search time.
  • Works like a book index.

πŸ”Ή Creating an Index

CREATE INDEX idx_students_course ON students(course_id);

βœ”οΈ Speeds up searches involving course_id.

πŸ”Ή Checking Execution Time

EXPLAIN QUERY PLAN 
SELECT * FROM students WHERE course_id = 1;

βœ”οΈ Shows whether the query is using an index.

πŸ”Ή Deleting an Index

DROP INDEX idx_students_course;

πŸ›  Exercise 2

  1. Create an index for the students' names.
  2. Run a SELECT query with and without the index.

πŸ“Œ Module 3: Transactions for Data Integrity (8 mins)

πŸ”Ή What is a Transaction?

  • Ensures multiple operations succeed or fail together.
  • Uses BEGIN, COMMIT, and ROLLBACK.

πŸ”Ή Example: Safe Bank Transfer

BEGIN TRANSACTION;

UPDATE students SET course_id = 2 WHERE name = 'Alice';

-- Simulate an error before committing
ROLLBACK; 

SELECT * FROM students;  -- Alice's course remains unchanged

βœ”οΈ ROLLBACK prevents incomplete operations from saving.

πŸ”Ή COMMIT: Finalizing Transactions

BEGIN TRANSACTION;

UPDATE students SET course_id = 2 WHERE name = 'Alice';
COMMIT;

SELECT * FROM students;  -- Alice's course is now updated

βœ”οΈ COMMIT permanently saves the changes.

πŸ›  Exercise 3

  1. Begin a transaction to update multiple students.
  2. Rollback before committing and check if data changes.

πŸ“Œ Module 4: Combining Joins, Indexing, and Transactions (7 mins)

πŸ”Ή Complex Query Example

BEGIN TRANSACTION;

SELECT students.name, courses.course_name
FROM students
JOIN courses ON students.course_id = courses.id
WHERE students.name LIKE 'A%';

COMMIT;

βœ”οΈ Finds students whose names start with 'A' and ensures query execution in a transaction.

πŸ”Ή Optimizing Queries

CREATE INDEX idx_courses_name ON courses(course_name);

βœ”οΈ Speeds up searching for courses by name.

πŸ›  Final Exercise

  1. Create a new table for enrollments and use a JOIN to show which student is in which course.
  2. Use transactions to ensure enrollment updates succeed.
  3. Optimize the query using an index.

🎯 Summary of the Tutorial

βœ”οΈ Module 1: Joins (Combining tables)
βœ”οΈ Module 2: Indexing (Faster queries)
βœ”οΈ Module 3: Transactions (Data integrity)
βœ”οΈ Module 4: Combining them in real-world queries


πŸ“Œ Next Steps ( We Will Study later !)

  • Try using foreign keys to enforce relationships.
  • Experiment with nested joins and multi-table indexes.
  • Learn about triggers for automated actions.

Would you like sample SQL scripts for practice? πŸš€

#8.1 SQLite tutorial basics

 Here's a 30-minute SQLite tutorial divided into four modules to explain CRUD principles for undergraduate students. Each module takes about 7-8 minutes and includes theory, examples, and exercises.


🎯 Goal of the Tutorial

  • Learn the basics of SQLite.
  • Understand CRUD (Create, Read, Update, Delete) operations.
  • Use SQLite commands to manage a database.

πŸ“ Module 1: Introduction to SQLite & Setting Up (7 mins)

πŸ”Ή What is SQLite?

  • A lightweight, self-contained database.
  • No need for a separate server (unlike MySQL/PostgreSQL).
  • Used in mobile apps, embedded systems, and local applications.

πŸ”Ή Installing SQLite

Windows:

  1. Download SQLite from SQLite official site.
  2. Extract and open the sqlite3.exe file.
  3. Run:
    sqlite3
    

Linux/macOS:

  1. Install via terminal:
    sudo apt install sqlite3   # Ubuntu/Debian
    brew install sqlite        # macOS
    
  2. Run SQLite:
    sqlite3
    

πŸ›  Exercise 1: Creating a Database

sqlite3 students.db

βœ”οΈ This creates a students.db file where we will store our tables.


πŸ“Œ Module 2: Creating and Reading Data (7 mins)

πŸ”Ή Creating a Table (C in CRUD)

We create a students table:

CREATE TABLE students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE,
    age INTEGER,
    course TEXT
);

πŸ”Ή Inserting Data

INSERT INTO students (name, email, age, course)
VALUES ('Alice', 'alice@example.com', 20, 'Computer Science');

πŸ”Ή Reading Data (R in CRUD)

SELECT * FROM students;

πŸ›  Exercise 2: Insert and Read

  1. Insert two more student records.
  2. Run SELECT * FROM students; to check.

✏️ Module 3: Updating and Deleting Data (7 mins)

πŸ”Ή Updating Data (U in CRUD)

Updating Alice’s course:

UPDATE students 
SET course = 'Data Science' 
WHERE name = 'Alice';

πŸ”Ή Deleting Data (D in CRUD)

DELETE FROM students WHERE name = 'Alice';

πŸ›  Exercise 3:

  1. Update another student’s age.
  2. Delete a student record.



πŸš€ Module 4: Advanced Queries & Best Practices (7 mins)

πŸ”Ή Filtering Data

SELECT * FROM students WHERE age > 18;

πŸ”Ή Sorting Data

SELECT * FROM students ORDER BY name ASC;

πŸ”Ή Counting Records

SELECT COUNT(*) FROM students;

πŸ›  Final Exercise

  1. Retrieve students older than 21.
  2. Count the number of students.

Dropping Tables and Databases in SQLite

SQLite allows you to delete tables using DROP TABLE, but it does not support dropping databases directly since an SQLite database is just a file.


πŸ”Ή Dropping a Table in SQLite

To delete a table along with all its data, use:

DROP TABLE table_name;

Example

DROP TABLE students;

βœ”οΈ This removes the students table permanently.
❗ Warning: This action cannot be undone.


πŸ”Ή Dropping a Database in SQLite

Since SQLite databases are just files, you delete a database by removing the database file from the system.

Steps to Drop an SQLite Database

  1. Find the database file (e.g., mydatabase.db).
  2. Delete it manually using the terminal or command prompt.

Using Command Line

Windows

del mydatabase.db

Linux/macOS

rm mydatabase.db

βœ”οΈ This permanently deletes the database file.
❗ Warning: This cannot be undone unless you have a backup.


πŸ”Ή Checking Before Dropping

Before dropping a table, check if it exists:

DROP TABLE IF EXISTS students;

βœ”οΈ This prevents errors if the table doesn’t exist.


πŸ”Ή Alternative: Clearing a Table Instead of Dropping

If you just want to clear all data but keep the table structure, use:

DELETE FROM students;

βœ”οΈ Removes all records but keeps the table.

OR

DELETE FROM students WHERE 1=1;

βœ”οΈ Same as above but can be used dynamically in scripts.

Would you like a script to automate table deletions? πŸš€



=======================================================================

🎯 Summary of the Tutorial

βœ”οΈ Module 1: Setup and creating a database
βœ”οΈ Module 2: Creating and reading records
βœ”οΈ Module 3: Updating and deleting data
βœ”οΈ Module 4: Advanced queries


πŸ“Œ Next Steps

  • Try integrating SQLite with Python, Node.js, or JavaScript.
  • Experiment with joins, indexing, and transactions.

Would you like me to prepare slides or code files for this tutorial? πŸš€

#8.0 SQLite Installation

 Installing SQLite depends on your operating system. Here’s how to install it on Windows, macOS, and Linux.


πŸ–₯️ Windows

Step 1: Download SQLite

  1. Go to the official SQLite download page:
    πŸ‘‰ https://www.sqlite.org/download.html
  2. Scroll to the section "Precompiled Binaries for Windows".
  3. Download: https://www.sqlite.org/2025/sqlite-tools-win-x64-3490100.zip
    • (SQLite  +Tools  +  DLL ) 

Step 2: Extract and Setup

  1. Extract the SQLite Tools ZIP file into d:\sqlite (or any folder of your choice).
  2. Copy the full path of the extracted folder (e.g., d:\sqlite).

Step 3: Add to System PATH

  1. Open Start Menu and search for "Environment Variables".
  2. Click Edit the system environment variables.
  3. Under System Properties, click Environment Variables.
  4. In System variables, select Path β†’ Click Edit.
  5. Click New, paste the path (d:\sqlite), and click OK.

Step 4: Verify Installation

  1. Open Command Prompt (cmd).
  2. Type:
    sqlite3
    
  3. You should see:
    SQLite version X.X.X
    Enter ".help" for usage hints.
    sqlite>
    
    If you see this, SQLite is installed successfully!

🍏 macOS

Option 1: Install via Homebrew (Recommended)

  1. Open Terminal and run:
    brew install sqlite
    
  2. Verify the installation:
    sqlite3 --version
    
    If it returns a version number, SQLite is installed.

Option 2: Install Manually

  1. Download the macOS binary from SQLite Download Page.
  2. Extract and move it to /usr/local/bin:
    sudo mv sqlite3 /usr/local/bin/
    
  3. Set permissions:
    chmod +x /usr/local/bin/sqlite3
    
  4. Verify:
    sqlite3 --version
    

🐧 Linux (Ubuntu, Debian, Fedora, etc.)

Install via Package Manager

For Ubuntu/Debian:

sudo apt update
sudo apt install sqlite3 libsqlite3-dev -y

For Fedora:

sudo dnf install sqlite sqlite-devel -y

For Arch Linux:

sudo pacman -S sqlite

Verify Installation

sqlite3 --version

If you see a version number, SQLite is installed successfully.


🎯 Next Steps

Now that SQLite is installed, you can:

  • Create a database:
    sqlite3 mydatabase.db
    
  • Create tables and insert data:
    CREATE TABLE employees (
        empid INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE
    );
    INSERT INTO employees (name, email) VALUES ('John Doe', 'john@example.com');
    
  • View data:
    SELECT * FROM employees;
    

You're ready to use SQLite! πŸš€ Let me know if you need help.

#7 CRUD Made Simple

 Here's a well-structured blog post based on your content:


CRUD Made Simple: A Step-by-Step Guide to Angular 19 CRUD Operations

Creating a CRUD (Create, Read, Update, Delete) application in Angular 19 has never been easier! In this tutorial, we'll build a simple employee management system using Bootstrap, Reactive Forms, and Local Storage.

Let's dive in! πŸš€


Step 1: Create a New Angular Project

First, create a new Angular project using the following command:

ng new ang19-crud

Navigate into the project folder:

cd ang19-crud

Start the development server:

ng serve

This will launch your Angular app at http://localhost:4200/. πŸŽ‰


Step 2: Install Bootstrap for Styling

To add Bootstrap, run:

npm i bootstrap

Then, update the styles section in angular.json to include Bootstrap:

"styles": [
  "./node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]

Now, your app is ready for a clean and responsive UI! 🎨


Step 3: Create the Employee Model

Inside the src/app folder, create a model folder and add a new file Employee.ts:

export class EmployeeModel {
  empid: number;
  name: string;
  city: string;
  state: string;
  emailId: string;
  contactNo: string;
  address: string;
  pinCode: string;

  constructor() {
    this.address = '';
    this.city = '';
    this.contactNo = '';
    this.emailId = '';
    this.empid = 1;
    this.name = '';
    this.state = '';
    this.pinCode = '';
  }
}

This model defines the structure of an employee object.


Step 4: Build the Employee List UI

Modify app.component.html to include the Employee List Table and Employee Form:

<div class="row">
  <!-- Employee List -->
  <div class="col-8">
    <div class="card">
      <div class="card-header bg-success">
        <h6>Employee List</h6>
      </div>
      <div class="card-body">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Sr No</th>
              <th>Name</th>
              <th>Contact No</th>
              <th>Email-Id</th>
              <th class="text-center">Action</th>
            </tr>
          </thead>
          <tbody>
            @for (item of employeeList; track $index) {
              <tr>
                <td>{{$index+1}}</td>
                <td>{{item.name}}</td>
                <td>{{item.contactNo}}</td>
                <td>{{item.emailId}}</td>
                <td class="text-center">
                  <button class="btn btn-primary" (click)="onEdit(item)">Edit</button>
                  <button class="btn btn-danger mx-2" (click)="onDelete(item.empid)">Delete</button>
                </td>
              </tr>
            }
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Employee Form -->
  <div class="col-4">
    <div class="card">
      <div class="card-header bg-success">New Employee</div>
      <div class="card-body">
        <form [formGroup]="employeeForm">
          <div class="row">
            <div class="col-12">
              <label>Name</label>
              <input type="text" formControlName="name" class="form-control">
            </div>
            <div class="col-6">
              <label>Email-Id</label>
              <input type="text" formControlName="emailId" class="form-control">
            </div>
            <div class="col-6">
              <label>Contact No</label>
              <input type="text" formControlName="contactNo" class="form-control">
            </div>
            <div class="col-6">
              <label>City</label>
              <input type="text" formControlName="city" class="form-control">
            </div>
            <div class="col-6">
              <label>State</label>
              <input type="text" formControlName="state" class="form-control">
            </div>
            <div class="col-6">
              <label>Pin Code</label>
              <input type="text" formControlName="pinCode" class="form-control">
            </div>
            <div class="col-12">
              <label>Address</label>
              <textarea formControlName="address" class="form-control"></textarea>
            </div>
          </div>
          <div class="row pt-2">
            <div class="col-6 text-center">
              <button class="btn btn-secondary" type="button" (click)="reset()">Reset</button>
            </div>
            <div class="col-6 text-center">
              @if(employeeForm.controls['empid'].value == '1') {
                <button class="btn btn-success" [disabled]="employeeForm.invalid" (click)="onSave()">Save</button>
              } @else {
                <button class="btn btn-warning" [disabled]="employeeForm.invalid" (click)="onUpdate()">Update</button>
              }
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

Step 5: Implement CRUD Operations in app.component.ts

Now, let's define CRUD functionalities:

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EmployeeModel } from './model/Employee';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  employeeForm: FormGroup;
  employeeObj: EmployeeModel = new EmployeeModel();
  employeeList: EmployeeModel[] = [];

  constructor() {
    this.createForm();
    const oldData = localStorage.getItem("EmpData");
    if (oldData) {
      this.employeeList = JSON.parse(oldData);
    }
  }

  reset() {
    this.employeeObj = new EmployeeModel();
    this.createForm();
  }

  createForm() {
    this.employeeForm = new FormGroup({
      empid: new FormControl(this.employeeObj.empid),
      name: new FormControl(this.employeeObj.name, [Validators.required]),
      city: new FormControl(this.employeeObj.city),
      address: new FormControl(this.employeeObj.address),
      contactNo: new FormControl(this.employeeObj.contactNo),
      emailId: new FormControl(this.employeeObj.emailId),
      pinCode: new FormControl(this.employeeObj.pinCode, [Validators.required, Validators.minLength(6)]),
      state: new FormControl(this.employeeObj.state)
    });
  }

  onSave() {
    this.employeeList.unshift(this.employeeForm.value);
    localStorage.setItem("EmpData", JSON.stringify(this.employeeList));
    this.reset();
  }

  onEdit(item: EmployeeModel) {
    this.employeeObj = item;
    this.createForm();
  }

  onUpdate() {
    const record = this.employeeList.find(m => m.empid == this.employeeForm.controls['empid'].value);
    if (record) {
      Object.assign(record, this.employeeForm.value);
    }
    localStorage.setItem("EmpData", JSON.stringify(this.employeeList));
    this.reset();
  }

  onDelete(id: number) {
    if (confirm("Are you sure you want to delete?")) {
      this.employeeList = this.employeeList.filter(m => m.empid !== id);
      localStorage.setItem("EmpData", JSON.stringify(this.employeeList));
    }
  }
}

Final Touch: Add Styling

In app.component.css:

.form-control {
  border: 1px solid gray !important;
}

πŸŽ‰ Conclusion

You've successfully built a simple Angular 19 CRUD application using Bootstrap and Local Storage. πŸš€

Would you like to extend this tutorial by integrating an API backend? Let me know in the comments! πŸ˜ƒ

Sunday, March 9, 2025

#6.4 Side Nav Bar - Demo

 Here's your content formatted as a blog post:


Angular 19 Side Navigation Bar Using Angular Material

πŸ”Ή Introduction

A Side Navigation Bar (Sidenav) is a crucial UI component for modern web applications, improving accessibility and navigation. In this guide, we’ll use Angular 19 and Angular Material to create a responsive Sidenav with routing and dynamic menu items.

πŸ‘‰ Reference: Angular Material Sidenav


πŸ“Œ Step 1: Create a New Angular Project

First, create a new Angular project:

ng new side-nav-bar
cd side-nav-bar
code .

Run the project:

ng serve

πŸ“Œ Step 2: Install Angular Material

To use Material components, install Angular Material:

ng add @angular/material

Choose a theme, and once installed, restart your development server:

ng serve

πŸ“Œ Step 3: Create the Angular Material Side Navigation Bar

We’ll modify app.component.html to include a sidenav.

πŸ“ Modify app.component.html

Replace the existing code with:

<mat-toolbar color="accent">
  <mat-toolbar-row>
    <button mat-icon-button (click)="sidenav.toggle();">
      <mat-icon>menu</mat-icon>
    </button>
    <h1>Angular Material Sidenav</h1>
  </mat-toolbar-row>
</mat-toolbar>

<mat-sidenav-container>
  <mat-sidenav #sidenav opened mode="side" [style.width]="'200px'">
    <mat-nav-list>
      @for(item of menuItems; track $index){
        <a mat-list-item [routerLink]="item.route">
          <mat-icon matListItemIcon>{{ item.icon }}</mat-icon>
          <span>{{ item.label }}</span>
        </a>
      }
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>

πŸ“Œ Step 4: Configure the Component Logic

Modify app.component.ts to include menu items dynamically.

πŸ“ Update app.component.ts

import { Component } from '@angular/core';
import { RouterModule, RouterOutlet } from '@angular/router';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatButtonModule } from '@angular/material/button';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    MatToolbarModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule,
    MatButtonModule,
    RouterModule
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'angular-sidenav';

  menuItems: any[] = [
    { icon: 'home', label: 'Home', route: 'home' },
    { icon: 'handshake', label: 'Partners', route: 'partners' },
    { icon: 'book', label: 'Training', route: 'training' },
    { icon: 'event', label: 'Events', route: 'event' },
    { icon: 'help', label: 'Support', route: 'support' }
  ];
}

πŸ“Œ Step 5: Style the Side Navigation Bar

πŸ“ Modify app.component.css

.mat-sidenav-container {
    height: 89vh;
}

.mat-sidenav-content {
    padding: 20px;
}

πŸ“Œ Step 6: Generate Components for Routing

Now, generate separate components for different sections of your app:

ng g c home
ng g c partners
ng g c training
ng g c events
ng g c support

πŸ“Œ Step 7: Configure Routing

Modify app.routes.ts to define application routes.

πŸ“ Update app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { PartnersComponent } from './pages/partners/partners.component';
import { TrainingComponent } from './pages/training/training.component';
import { EventsComponent } from './pages/events/events.component';
import { SupportComponent } from './pages/support/support.component';

export const routes: Routes = [
    { path: '', pathMatch: 'full', redirectTo: 'home' },
    { path: 'home', component: HomeComponent },
    { path: 'partners', component: PartnersComponent },
    { path: 'training', component: TrainingComponent },
    { path: 'event', component: EventsComponent },
    { path: 'support', component: SupportComponent }
];

🎯 Final Steps

Run your Angular project again:

ng serve

Open your browser and navigate to http://localhost:4200/. πŸŽ‰


βœ… Summary

βœ” We created an Angular 19 project with Angular Material.
βœ” We added a dynamic side navigation bar.
βœ” We generated components and configured routing.
βœ” We applied styling and added menu icons.

πŸš€ Your Angular 19 Side Navigation Bar is ready! Let me know if you need further enhancements. 😊

Thursday, March 6, 2025

#6.3 Reactive Form Validation

🎯 React Form Validation (Because Forms Need Rules!)

Angular isn’t the only one that needs validationβ€”React does too! Let’s build a React Form with validation using ReactiveFormsModule. πŸ—οΈ


πŸš€ Step 1: Set Up app.component.ts

Modify app.component.ts to create a React-based form:

import { ReactiveFormsModule, Validators } from '@angular/forms';
import {Component} from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})

export class AppComponent {
  title = 'reactform';
  profileForm = new FormGroup({
      firstName: new FormControl('', [Validators.required]),
      lastName: new FormControl('', [Validators.required, Validators.minLength(5)]),
      email: new FormControl('', [Validators.required, Validators.email]), 
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl('Tamil Nadu'),
      zip: new FormControl(''),
    });
}

🎨 Step 2: Create the Form in app.component.html

Modify app.component.html to include input fields and validation:

<h1>Reactive Form & Validation</h1>
<form [formGroup]="profileForm" (ngSubmit)="onUserSave()">
  <label>First Name: </label>
  <input type="text" formControlName="firstName">
  <div class="text-danger" *ngIf="profileForm.controls['firstName'].errors?.['required']">This is Required</div>

  <label>Last Name: </label>
  <input type="text" formControlName="lastName">
  <div class="text-danger" *ngIf="profileForm.controls['lastName'].errors?.['required']">This is Required</div>
  <div class="text-danger" *ngIf="profileForm.controls['lastName'].errors?.['minlength']">Minimum Length: 5 characters</div>

  <label>Email: </label>
  <input type="email" formControlName="email">
  <div class="text-danger" *ngIf="profileForm.controls['email'].errors?.['required']">Email is required</div>
  
  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>

Modify app.component.css:

.card {
  flex: auto;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  background-color: aquamarine; 
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.text-danger {
    color: red;
}

πŸ’… This makes our form look less boring and adds a light shadow effect.


πŸŽ‰ Summary

βœ… We built a React-based form with validation. βœ… Required fields and error messages are handled. βœ… Submit button only works when everything is correct.

πŸ’‘ Now your React forms are smarter than ever! Keep coding and happy React-ing! πŸš€πŸ”₯

#6.2 Template Form Validation


🎯 Form Validation in Angular Template Forms

Validation: Because Users Love Making Mistakes! 😜

Ever filled out a form and got an error? Yep, we’re here to make sure those mistakes get caught before they cause chaos! Let’s dive into form validation in Angular template-driven forms.


πŸš€ Step 1: Set Up the HTML Form

Modify app.component.html to create a template form with validation:

<h1>Template Form Validation</h1>
<form #userForm="ngForm">
  <div class="card">
    
    <label>First Name</label>
    <input type="text" [(ngModel)]="userObj.fName" #fname="ngModel" 
            name="fName" required><br><br>
    <div class="text-danger">
      <span *ngIf="fname.errors?.['required'] && fname.touched">
            This is Required<br><br></span>
    </div>

    <label>Last Name</label>
    <input type="text" [(ngModel)]="userObj.lName" #lname="ngModel" 
        name="lName" required minlength="5"><br><br>
    <div class="text-danger">
      <span *ngIf="lname.errors?.['required'] && 
            lname.touched">This is Required<br><br></span>
      <span *ngIf="lname.errors?.['minlength'] &&
             lname.touched">Minimum Length: 5 characters<br><br></span>
    </div>

    <label>Email</label>
    <input type="email" [(ngModel)]="userObj.email" 
                #Email="ngModel" name="email" required><br><br>
    <div class="text-danger">
      <span *ngIf="Email.errors?.['required'] &&
                     Email.touched">This is Required<br><br></span>
      <span *ngIf="Email.errors?.['email']">
                    Enter a valid email format! πŸ“§<br><br></span>
    </div>

    <button type="submit" [disabled]="userForm.invalid" 
            (click)="onSave()">Submit</button>
  </div>
</form>

πŸ”΄ Validation Rules:

  • First Name: Required
  • Last Name: Required, at least 5 characters
  • Email: Required, must be a valid email
  • Submit button only works when the form is valid πŸŽ‰

πŸ’» Step 2: Modify app.component.ts

Let’s handle the form data:

import { NgIf } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [FormsModule, NgIf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'formvalid';

  userObj: any = {
      fName: '',
      lName: '',
      email: ''
  } 
  
  onSave(){
    console.log("Form Submitted! πŸš€", this.userObj);
  }
}

🎯 When the form is submitted, it logs the data. (Replace console.log with a real API call if needed!)


🎨 Step 3: Styling It Up! (Because Ugly Forms Suck πŸ˜†)

Modify app.component.css:

.card {
  flex: auto;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  background-color: aquamarine; 
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.text-danger {
    color: red;
}

πŸ’… This makes our form look less boring and adds a light shadow effect.


πŸ”₯ Summary

βœ… We built a template-driven form with validation. βœ… We added error messages that show up when users mess up. βœ… We made sure the submit button is disabled unless everything is valid. βœ… We styled the form to look nice and clean!

πŸ‘ Congratulations! Now your forms are smarter than ever. Keep coding and happy Angular-ing! πŸš€πŸ”₯

Tuesday, March 4, 2025

#6.1 Reactive Form Group

Step 1: Create a New Angular Project

ng new reactiveform
cd reactiveform
code .

Step 2: Create a Reactive Form 

Modify app.component.ts to import necessary modules:

import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  profileForm = new FormGroup({
          name: new FormControl('RMC'),
          password: new FormControl('098765'),
          email: new FormControl(),
          mobile: new FormControl(),
 })

 submitData() {
    console.log(this.profileForm.value.name);
 }
  setValues() {
    this.profileForm.setValue({
      name: 'Peter',
      password: '12345121212',
      email: 'a123@a.com',
      mobile: '123456789'
    })
  }
}

Step 3: Modify app.component.html to Create the Form

<h1>Basic React Form</h1>
<form [formGroup]="profileForm">
  <label>Name: </label><br>
  <input type="text" placeholder="Enter your name" formControlName="name"><br><br>
  <label>Password: </label><br>
  <input type="text" placeholder="Enter your password" formControlName="password"><br><br>
  <label>email: </label><br>
  <input type="text" placeholder="Enter your email"  formControlName="email"><br><br>
  <label>Mobile: </label><br>
  <input type="text" placeholder="Enter yourMobile"  formControlName="Mobile"><br><br>
  <button (click) = 'submitData()'>Submit</button><br>
  <button type="button" (click) = 'setValues()'>SetData</button><br>
</form>

<hr>
Check: {{this.profileForm.value.name}}

πŸš€ Summary

  • We created a reactive form using Angular Material.
  • πŸŽ‰ Congratulations! You just built an reactive basic Form! Keep experimenting! πŸ’‘

#6 Session 5: Reactive Form Basics

 Here are the lecture notes for Session 5: Forms & Validation (2 hours) with a step-by-step hands-on guide.


Session 5: Reactive Form

Learning Objectives

βœ… Understand the difference between Template-Driven Forms and Reactive Forms
βœ… Learn how to create Angular Forms with validation
βœ… Implement custom validation and error handling
βœ… Hands-on practice with forms using Reactive Forms and Template-Driven Forms


1. Introduction to Angular Forms (15 mins)

What are Angular Forms?

Forms in Angular allow users to input data. There are two approaches:

Type Features
Template-Driven Forms Simple, uses HTML and Angular directives like ngModel
Reactive Forms More powerful, programmatic form control with FormGroup and FormControl

Why Use Forms?

βœ” Collect and process user data
βœ” Validate input before submission
βœ” Handle errors and display messages


When to Use Reactive Forms?

Answer: When things get complex! But hey, let’s start simple so our brains don’t explode. πŸš€


Step 1: Create a New Angular Project

ng new form1
cd form1
code .

Step 2: Building a Simple Form (Baby Steps πŸ‘Ά)

Modify app.component.html to create a basic form:

<h1>Basic React Form</h1>
<input type="text" placeholder="Enter your name"><br>
<input type="text" placeholder="Enter your password"><br>
<input type="text" placeholder="Enter your email"><br>
<button>Add Info</button>

πŸš€ Looks simple, right? But let’s make it smarter!


Step 3: Making It Reactive πŸ’ͺ

Modify app.component.ts:

import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  name = new FormControl();
  password = new FormControl();
  email = new FormControl();
  mobile = new FormControl();
}

Modify app.component.html to bind the inputs:

<h1>Basic React Form</h1>
<input type="text" placeholder="Enter your name" [formControl]="name"><br><br>
<input type="text" placeholder="Enter your password" [formControl]="password"><br><br>
<input type="text" placeholder="Enter your email" [formControl]="email"><br><br>
<input type="text" placeholder="Enter your Mobile" [formControl]="mobile"><br><br>
<button>Add Info</button>

<br>
Values Entered:
<br>
{{name.value}}<br>
{{password.value}}<br>
{{email.value}}<br>
{{mobile.value}}<br>

Now, when you type something, it updates automatically! Cool, right? 😎

Run the project:

ng serve

Check it out in the browser!


Step 4: Get Values from the Form πŸ•΅οΈβ€β™‚οΈ

Modify app.component.ts:

export class AppComponent {
  name = new FormControl();
  password = new FormControl();
  email = new FormControl();
  mobile = new FormControl();

  getValue() {
    console.log(this.name.value);
    console.log(this.password.value);
    console.log(this.email.value);
    console.log(this.mobile.value);
  }
}

Modify app.component.html to add a button:

<button (click)="getValue()">Get Info</button>

Now when you click the button, check the console. It prints what you typed! πŸ–¨οΈ


Step 5: Set Values in the Form (Magic Trick 🎩🐰)

Modify app.component.ts:

setValue() {
  this.name.setValue("rmc");
  this.password.setValue("immbiz");
  this.email.setValue("a@a.com");
  this.mobile.setValue("1234567890");
}

Modify app.component.html:

<button (click)="setValue()">Set Info</button>

πŸ”„ Click the button, and BOOM! The fields are auto-filled.


Step 6: Set Default Values (Because We’re Lazy πŸ€·β€β™‚οΈ)

Modify app.component.ts:

export class AppComponent {
  name = new FormControl('RMC');
  password = new FormControl('ABCDEFGHIJ');
  email = new FormControl('a@a.com');
  mobile = new FormControl('09080750000');
}

Now, when the page loads, the fields already have values. Nice, right? πŸ˜‰


πŸš€ Summary

  • We started with a simple form.
  • We made it reactive using FormControl.
  • We learned to get values and set values dynamically.
  • We even added default values (because why type when you don’t have to?).

πŸŽ‰ Congratulations! You just built your first Angular Reactive Form! Keep experimenting! πŸ’‘

😊

Monday, March 3, 2025

#5 Session 4: Routing & Navigation (2 Hours)

 Here are the lecture notes for Session 4: Routing & Navigation (2 hours) with a step-by-step hands-on guide.

Session 4: Routing & Navigation (2 Hours)

Learning Objectives

βœ… Understand Angular Routing and how it works
βœ… Learn how to create and configure Routes
βœ… Implement Router Links, Route Parameters, and Navigation
βœ… Hands-on practice with a Multi-Page Angular App


1. Introduction to Angular Routing (20 mins)

What is Routing?

  • Routing allows navigation between different pages in an Angular application without full-page reloads.
  • Uses Angular's RouterModule to define paths and link components.

Routing Concepts

Feature Description
RouterModule Enables routing in an Angular app
Routes Array Defines the application’s paths
RouterOutlet Acts as a placeholder for route components
RouterLink Enables navigation between routes



Check Here : https://ametodl.blogspot.com/2025/02/angular-18-navigation-for-immss.html


Once you tried the above You will get the Screen similar to one below:



6. Summary & Q&A (15 mins)

βœ… What We Learned Today:
βœ” Setting Up Angular Routing & Router LinksNext Session: Forms & Validation πŸš€


Would you like any additional topics or modifications? 😊

#11 @Output

  Understanding @Output() in Angular 19 The @Output() decorator in Angular 19 is used to send data from a child component to a parent co...