Wednesday, 30 November 2022

Angular #7 Service

Service:

Service once written and injected to all components in an app.

Service in Angular is a normal class with properties and reusable functions. These functions are called angular components, directives, and other services.

  • Easily share data between multiple components

Method 1 - Angular Service 

Exercise 12

Step 1: 

ng new service-demo

Choose y and css.   

Step 2:

Create service by

ng g s employee

Step 3:

open app.module.ts and add the following

import {EmployeeService} from './employee.service';


Step 4:

Create a file called as products.ts under app directory

export class Product {
 
    constructor(productID:number,    name: string ,   price:number) {
        this.productID=productID;
        this.name=name;
        this.price=price;
    }
 
    productID:number ;
    name: string ;
    price:number;
 
}


Step 5

Create a file product.service.ts

import {Product} from './product'
 
export class ProductService{
 
    public  getProducts() {
 
        let products:Product[];
 
        products=[
            new Product(1,'Tesla Phone',500),
            new Product(2,'iPhone',750),
            new Product(3,'Samsung TV',100)
        ]
 
        return products;              
    }
}
 

Step 6 :

Modify app.component.ts as follows

add  imports for product and product service and modify class AppComponent as below 

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

import { ProductService } from './product.service';
import { Product } from './product';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})

export class AppComponent {
  products!: Product[];
  productService;

  constructor() {
    this.productService = new ProductService();
  }

  getProducts() {
    this.products = this.productService.getProducts();
  }

}

Note products! assertion here.


Step 7

Modify app.component.html with the following

<div class="container">
    <h1 class="heading"><strong>Services </strong>Demo</h1>
    <button type="button" (click)="getProducts()">Get Products</button>
    <div class='table-responsive'>
    <div>
      <table class='table'>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let product of products;">
            <td>{{product.productID}}</td>
            <td>{{product.name}}</td>
            <td>{{product.price}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

Step 8: In Terminal Prompt, Install Bootstrap 4

npm install bootstrap@4  

Modify styles section in angular.json file

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

Step 9:

Run in terminal 

ng serve

open localhost:4200 in browser and click getProducts Button

to check the similar output in browser window

Method 2 - Angular Service[DI].... 


Create a angular project in stackblitz
https://stackblitz.com/edit/angular

create services folder under app
create a file data.service.ts under services directory. Add the following contents:

import {Injectablefrom '@angular/core';

@Injectable()
export class DataService {
  count=0;
}

app.component.ts

import { Component } from '@angular/core';
import { DataService } from './services/data.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  constructor(private dataServiceDataService){}
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import {DataServicefrom './services/data.service'
@NgModule({
  imports:      [ BrowserModuleFormsModule ],
  declarations: [ AppComponentHelloComponent ],
  bootstrap:    [ AppComponent ],
  providers: [DataService]
})
export class AppModule { }

app.component.html 

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
{{dataService.count}}
Check 0 appears in browser window

hello.component.ts


import { ComponentInput } from '@angular/core';
import { DataService } from './services/data.service';
@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!{{dataService.count}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() namestring;

  constructor(private dataServiceDataService){}
}

Modify app.component.ts with incrementCount, decrementCount functions.

import { Component } from '@angular/core';
import { DataService } from './services/data.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  constructor(private dataServiceDataService){}
  incrementCount(){
    this.dataService.count++;
  }
  decrementCount(){
    this.dataService.count--;
  }

}

modify app.component.html as follows
<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
{{dataService.count}}

<button >Increment</button>
<button>Subtract</decrement>



You can check in the browser (||r as shown below)

Hello Angular!50

Start editing to see some magic happen :)

50 







Angular #6 [ngClass]

 Ex. 11

[ngClass] Directive adds and removes CSS classes in an HTML element.

create class-demo project by 

Open styles.css in app root. Add the following and save:

.mystyle1{
    color: yellow;
    background-color: red;
    font-size: 16px;
}
.mystyle2
{
    height: 200px;
}

Open app.component.html

Delete the old contents, add the following code and save.

<P>ngClass Demo</P>
<div [ngClass] = "{mystyle1: true}">
  This is with red background and yellow text ie. mystyle1
</div>
 
<div [ngClass] = "{mystyle2: true}">
  This is with height 200px ie. mystyle2
</div>

<div [ngClass] = "['mystyle1', 'myclass2']">
  This is with red background and yellow text + height 200 pixel <br>
  ie. myclass1, mystyle2
</div>

Open browser with localhost:4200 to check the screen similar to this for ngClass Demo

Happy Classing Angular!!!


Friday, 25 November 2022

Angular #5 with JSON

Ex 10

Angular with MongoDB integration

Ref : https://www.freakyjolly.com/angular-12-how-to-load-json-data-from-assets-folder/

Step 1

Create a new app by 

ng new json-demo

cd json-demo

code .  to open Visual Studio Code Editor

open app.component.ts file

add

import EmployeesJson from '../assets/employee.json';

and modify AppComponent class by

interface EMPLOYEE {
  ids: number;
  name: string;
}

export class AppComponent {
  title = 'Demo for angular-json interaction';
  Employees: EMPLOYEE[] = EmployeesJson;

  constructor(){
    console.log(this.Employees);
  }

Step 2 

Create JSON File: employees.json  in assets Folder
[
    { "ids": 102, "name": "Dr. Nice" },
    { "ids": 103, "name": "Bombasto" },
    { "ids": 104, "name": "Celeritas" },
    { "ids": 105, "name": "Magneta" },
    { "ids": 106, "name": "RubberMan" },
    { "ids": 107, "name": "Dynama" },
    { "ids": 108, "name": "Dr. IQ" },
    { "ids": 109, "name": "Magma" },
    { "ids": 200, "name": "Tornado" }
  ]

Step 3 
In app folder, create a file name as json-typings.d.ts +  add the following contents and save.
declare module "*.json" {
    const value: any;
    export default value;
    }
Step 4 
Modify file: app.component.html  in app folder as below:
<div>
  <table class="table">
    <thead>
        <tr>
          <th>Ids</th>
          <th>Name</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let employee of Employees">
        <th>{{ employee.ids }}</th>
        <td>{{ employee.name }}</td>
      </tr>
    </tbody>
  </table>
</div>


Step 5 
Modify file: app.component.html  in app folder as below:
 <div class="container mt-5">
  <h1>{{title}}</h1>
  <div>
  <table class="table">
    <thead>
        <tr>
          <th>Ids</th>
          <th>Name</th>
        </tr>
    </thead>
    <br>
    <tbody>
      <tr *ngFor="let employee of Employees">
        <th scope="row">{{ employee.ids }}</th>
        <td style="color: #ff00ff">{{ employee.name }}</td>
      </tr>
    </tbody>
  </table>
</div>
Step 6: 

Install bootstrap by this command in New Terminal of VS code Editor

npm install bootstrap --save

After bootstrap installation: Open angular.json file.
update "styles.css" file at app  root with 

body {background-color: coral;}

In terminal type:

ng serve -o  

Check the browser window will appear similar to this:




Happy ☺☺☺☺Angular  App Development!!!



 

Thursday, 24 November 2022

Angular #4 Routing

Angular 19 Routing - Step-by-Step Guide with Code 🚀

📌 What is Routing in Angular?

Routing allows navigation between different components without refreshing the page. It helps create Single Page Applications (SPAs).


🔹 Step 1: Create a New Angular App

ng new angular-routing-example --standalone

📌 Flags Used:

  • --standalone: Creates the app using Standalone Components (Angular 16+).

🔹 Step 2: Generate Components

cd angular-routing-example
ng g c home --standalone
ng g c about --standalone

📌 This creates two components:

  • HomeComponent (home.component.ts)
  • AboutComponent (about.component.ts)

🔹 Step 3: Define Routes in app.routes.ts

Create a new file:
📌 src/app/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 }, // Default Route
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
];

📌 Explanation:

  • '/' → Loads HomeComponent by default.
  • '/home' → Navigates to Home page.
  • '/about' → Navigates to About page.

🔹 Step 4: Update app.component.ts

📌 Modify app.component.ts

import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { routes } from './app.routes';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule.forRoot(routes)],  // ✅ Import RouterModule with routes
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {}

🔹 Step 5: Add Navigation Links in app.component.html

📌 Modify app.component.html

<nav>
  <a routerLink="/home">Home</a> |
  <a routerLink="/about">About</a>
</nav>

<router-outlet></router-outlet>

📌 Explanation:

  • <a routerLink="/home"> → Clicking navigates to /home.
  • <a routerLink="/about"> → Clicking navigates to /about.
  • <router-outlet></router-outlet> → Loads the respective component.

🔹 Step 6: Run the Application

ng serve

📌 Open http://localhost:4200 in your browser.

  • Click Home → Loads HomeComponent.
  • Click About → Loads AboutComponent.

🎯 Final Folder Structure

angular-routing-example/
│── src/
│   ├── app/
│   │   ├── app.component.ts
│   │   ├── app.component.html
│   │   ├── app.routes.ts  ✅ Routes File
│   │   ├── home/
│   │   │   ├── home.component.ts
│   │   │   ├── home.component.html
│   │   ├── about/
│   │   │   ├── about.component.ts
│   │   │   ├── about.component.html

🔥 Conclusion

✅ Now, you have a fully functional Angular Routing Example!
✅ Clicking the Home and About links will load different pages.
🚀 Happy Coding! 😎

Let me know if you need more help, bro!



Angular Routing Guide for Angular <16

Setting Up Routing in Angular

Follow these steps in the command prompt:

  1. Create a new Angular project

    ng new router-example --standalone
    
    • Select Y for Routing
    • Choose CSS for the stylesheet
  2. Navigate into the project directory

    cd router-example
    
  3. Generate components

    ng g c student
    ng g c subject
    
  4. Open the project

    code .
    

    (Or open the folder manually in VS Code)

  5. Modify app.module.ts

    Open src/app/app.module.ts and update the imports array:

    import { RouterModule } from '@angular/router';
    
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot([
          { path: 'student', component: StudentComponent },
          { path: 'subject', component: SubjectComponent },
        ]),
      ],
    })
    
  6. Modify app.component.html

    Delete existing content and replace with:

    <app-student></app-student>
    <app-subject></app-subject>
    
  7. Run the project

    ng serve
    

    Open http://localhost:4200 in a browser to check if the app is working.

Adding Navigation

  1. Modify app.component.html

    <nav>
      <a class="button" routerLink="/student">Student List</a> |
      <a class="button" routerLink="/subject">Subject List</a>
    </nav>
    <router-outlet></router-outlet>
    
    • This will add navigation buttons for Student and Subject.
  2. Modify app.component.css

    .button {
        background: linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
        border-radius: 6px;
        border: 1px solid #dcdcdc;
        cursor: pointer;
        color: #666;
        font-size: 15px;
        font-weight: bold;
        padding: 6px 24px;
        text-decoration: none;
    }
    
    .activebutton {
        background: linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
        border: 1px solid #84bbf3;
        color: #fff;
    }
    

Displaying Data in Components

  1. Modify subject.component.ts

    export class SubjectComponent {
      subjects = [
        { id: 12, name: 'Networks' },
        { id: 13, name: 'C' },
        { id: 14, name: 'C++' },
        { id: 15, name: 'Angular' },
        { id: 16, name: 'React' },
        { id: 17, name: 'Java' },
        { id: 18, name: 'Python' },
        { id: 19, name: 'HTML' },
        { id: 20, name: 'CSS' }
      ];
    }
    
  2. Modify student.component.ts

    export class StudentComponent {
      students = [
        { id: 102, name: 'Dr. Nice' },
        { id: 103, name: 'Bombasto' },
        { id: 104, name: 'Celeritas' },
        { id: 105, name: 'Magneta' },
        { id: 106, name: 'RubberMan' },
        { id: 107, name: 'Dynama' },
        { id: 108, name: 'Dr. IQ' },
        { id: 109, name: 'Magma' },
        { id: 200, name: 'Tornado' }
      ];
    }
    
  3. Modify subject.component.html

    <div *ngFor="let s of subjects">
      <div style="color: blue">
        {{s.id}}: {{s.name}}
      </div>
    </div>
    
  4. Modify student.component.html

    <div *ngFor="let s of students">
      <div style="color: blue">
        {{s.id}}: {{s.name}}
      </div>
    </div>
    

Final Testing

  • Run ng serve and open http://localhost:4200 to verify the output.

Exercise

  1. Modify app.component.css with:

    .button {
        box-shadow: inset 0 1px 0 0 #ffffff;
        background: linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
        border-radius: 6px;
        border: 1px solid #dcdcdc;
        display: inline-block;
        cursor: pointer;
        color: #666;
        font-size: 15px;
        font-weight: bold;
        padding: 6px 24px;
        text-decoration: none;
    }
    
    .activebutton {
        background: linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
        border: 1px solid #84bbf3;
        color: #ffffff;
    }
    
  2. Modify the first <a> tag in app.component.html:

    <a class="button"
       routerLink="/student"
       routerLinkActive="activebutton"
       ariaCurrentWhenActive="page">Student List</a> |
    

Check the browser output to see the updated navigation. Happy Learning Angular! 🚀


Monday, 21 November 2022

Angular 3 Structural Directives(+/- components in HTML View)

More Angular Magic! 🎩✨

*EX 5: ngFor Directive (Looping Through Data)

📌 How to Use ngFor Directive in Angular 19 (Step by Step)

The ngFor directive in Angular helps us display lists by looping through arrays. Here’s a simple guide to using ngFor in Angular 19 with standalone components.


🔹 Step 1: Create a New Angular App

Open your terminal and run the following command to create a new Angular project:

ng new ngfor-example --standalone
  • --standalone flag tells Angular not to create app.module.ts (since Angular 19 uses standalone components).

After running the command, move into the project folder:

cd ngfor-example

🔹 Step 2: Define an Array in app.component.ts

Inside the src/app/app.component.ts file, add a list of students:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgFor } from '@angular/common'; // ✅ Import NgFor


@Component({
  selector: 'app-root',
  standalone: true,
  import { NgFor } from '@angular/common';  // ✅ Import NgFor
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  imports:[F]  
})
export class AppComponent {
  students = [
    { id: 101, name: 'Alice' },
    { id: 102, name: 'Bob' },
    { id: 103, name: 'Charlie' },
    { id: 104, name: 'David' }
  ];
}

Explanation:

  • We define a list of students inside the students array.
  • Each student has an ID and Name.
  • This data will be displayed in the browser.

🔹 Step 3: Use ngFor in app.component.html

Modify the file src/app/app.component.html to display the student list:

<h2>Student List</h2>
<ul>
  <li *ngFor="let student of students">
    {{ student.id }} - {{ student.name }}
  </li>
</ul>

Explanation:

  • *ngFor="let student of students" → Loops through the students array.
  • Inside <li>, it displays ID and Name of each student.

🔹 Step 4: Run the Application

Start your Angular app by running:

ng serve

Now, open http://localhost:4200/ in a browser, and you will see the list of students displayed. 🎉




🔹 Step 5 (Optional): Add Index & Optimize Using trackBy

You can display the index number of each student and optimize performance using trackBy.

Update app.component.html

<h2>Student List</h2>
<ul>
  <li *ngFor="let student of students; let i = index; trackBy: trackById">
    {{ i + 1 }}. {{ student.id }} - {{ student.name }}
  </li>
</ul>

Update app.component.ts

trackById(index: number, student: any) {
  return student.id;
}

Explanation:

  • let i = index → Displays the position of each student.
  • trackBy: trackById → Helps Angular track elements by ID (improves performance).

🎯 Conclusion

1️⃣ ngFor helps loop through an array to display lists dynamically.
2️⃣ We created an array of students and displayed it using *ngFor.
3️⃣ The app was created using standalone components (no app.module.ts).
4️⃣ We added index numbers and used trackBy for better performance.

Now you know how to use ngFor in Angular 19! 🚀🔥

💡 Try modifying the list and see how it updates in real-time. 😎 Let me know if you need more help, bro!*EX 6: ngIf Directive (Conditional Rendering)

Want to show or hide elements dynamically? Use *ngIf!

Step 1: Add a Display Condition

Open src/app/app.component.ts and add:

    import { NgIf } from '@angular/common';                in the beginning
    imports: [FormsModule, NgFor, NgIf],                      in the @component decorator

export class AppComponent {
    displayButton: boolean = true;
}

*Step 2: Use ngIf in HTML

Edit src/app/app.component.html:

<div>
  <div *ngIf="displayButton">
     Message will disappear when you click this button
     <button class="btn btn-success" (click)="displayButton = false;">Click Me to Hide</button>
  </div>
</div>

Step 3: Run the Project

ng serve

Go to http://localhost:4200 and click the button—the message will disappear!

EX 7: ngStyle Directive (Dynamic Styling)

Using NgStyle Directive in Angular (Step-by-Step Guide)

The NgStyle directive in Angular allows you to dynamically apply CSS styles to elements based on component data.


🔹 Step 1: Create a New Angular App

If you don’t have an Angular project, create one using:

ng new ngstyle-example --standalone
cd ngstyle-example
code .

🔹 Step 2: Modify app.component.ts

Make sure you import NgStyle in the imports[] array of @Component() if using Angular 16+ (standalone mode).

📌 app.component.ts

import { Component } from '@angular/core';
import { NgFor, NgIf, NgStyle } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  imports: [NgStyle, NgFor, NgIf]  // ✅ Import NgStyle
})
export class AppComponent {
  isHighlighted = true;
  textColor = 'blue';
  bgColor = 'yellow';

  changeStyle() {
    this.isHighlighted = !this.isHighlighted;
    this.textColor = this.isHighlighted ? 'blue' : 'red';
    this.bgColor = this.isHighlighted ? 'yellow' : 'lightgray';
  }
}

🔹 Step 3: Update app.component.html to Use NgStyle

📌 app.component.html

<h2 [ngStyle]="{'color': textColor, 'background-color': bgColor, 'padding': '10px'}">
  This text changes color dynamically
</h2>

<button (click)="changeStyle()">Toggle Style</button>
<div *ngFor = "let i of [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]">
  <div *ngIf = "(i%2 != 0)" [ngStyle]="{'background-color':'green'}">
      <li><button>{{i}}</button></li>
  </div>
  <div *ngIf = "(i%2 === 0)" [ngStyle]="{'background-color':'red'}">
      <li><button>{{i}}</button></li>
  </div>
</div>

🔹 Explanation:

  • [ngStyle] applies dynamic styles to the <h2> element.
  • The button toggles textColor and bgColor when clicked.

🔹 Step 4: Run the Angular App

Start the Angular server:

ng serve

Open your browser and go to:

http://localhost:4200

Now, clicking the "Toggle Style" button will change the text color and background color dynamically! 🎨🎉




🚀 Summary

  • NgStyle dynamically applies inline CSS.
  • NgStyle takes an object with key-value pairs.
  • ✅ Works with standalone components in Angular 16+.

Let me know if you need more help, bro! 😎🔥

EX 8: Pipes (Transforming Data)

Need to format text quickly? Pipes make it super easy!

Step 1: Add Text Transformations

Open src/app/app.component.ts and add:

import { UpperCasePipe } from '@angular/common';   in the beginning
imports: [NgStyle, UpperCasePipe] in @Component decorator

export class AppComponent {
    textPipe = 'lower case to be converted to uppercase';
}

Step 2: Use Pipes in HTML

Edit src/app/app.component.html:

<span style="color:blue">{{ textPipe | uppercase }}</span> 
Step 3: Run the Project
ng serve

Go to http://localhost:4200 and check the text transformations!


Happy Learning Angular! 🚀😃

Angular 18 Navigation for iMMSS

  🚀 Setting Up Angular Routing - The Fun Way! 😆 Hey there, future Angular ninjas! 🥷 If you’re new to Angular and struggling with routing...