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! 🚀😃


Actual Hands On Output: Tried in Old Version Older Version

EX 5 : 

*ngFor Directivecd c

Create a new Angular Application in Visual Studio IDE Terminal

ng new EX5

Open folder EX5 and open src\app\app.component.html    file and add the following contents and save.

<div *ngFor = "let i of [1,3,5,7,9,11,12,14,15]">
  <li>No is : {{i}}<br></li>
</div>

run 

ng serve in Terminal. 

Once you get compiled successfully message, 

  1. Open http://localhost:4200 in any browser to check the following o/p:  
  • No is : 1
  • No is : 3
  • No is : 5
  • No is : 7
  • No is : 9
  • No is : 11
  • No is : 12
  • No is : 14
  • No is : 15   
  • -----------------------------------------------------------------------------------------------------------------------------

    EX 6 

    *ngIf Directive

    Open file src\app\app.component.ts file and add the displayButton object as shown below:

    export class AppComponent {
        displayButton: boolean = true;
    }


    Open  src\app\app.component.html    file and add the following contents and save.

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

    run 

    ng serve in Terminal. 

    Once you get compiled successfully message, Open http://localhost:4200 in any browser to check the following o/p initially:  

    Message will disappear when you click the button. with Click me to Hide Button. Once you click the button the browser screen will be blank.

    ---------------------------------------------------------------------------------------------------------------------------

    EX 7

    ngStyle Directive

    Open  src\app\app.component.html    file and add the following contents and save.

    <!-- //ngSTyle : changes the look and Behaviour of Web Page -->
    <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>

    run by ng serve in Terminal. 

    Once you get compiled successfully message, Open http://localhost:4200 in any browser to check the following o/p:  

    You will get screen like this


    EX8

    Pipes

    Open file src\app\app.component.ts file and add the displayButton object as shown below:

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

    Open  src\app\app.component.html    file and add the following contents and save.

    <div>
      Original Text:&nbsp;{{textPipe}}<br>
      To lowercase :<span style="color:'green'">&nbsp;{{textPipe |  lowercase}}</span>---> all Lowerase<br>
      To uppercase :<span style="color:'blue'">&nbsp;{{textPipe |  uppercase}}</span>---> all uppercase<br>
      Slicing:<span style="color:'red'">{{textPipe | slice:0:5}}</span>--->First 5 charecters of the original text<br>
    </div>

    run ng serve in Terminal. 

    Once you get compiled successfully message, Open http://localhost:4200 in any browser to check the following o/p initially:  

    In browser:

            Original Text: First Pipe
            To lowercase : first pipe---> all Lowerase
            To uppercase : FIRST PIPE---> all uppercase
            Slicing:First--->First 5 charecters of the original text

    Happy Learning Angular! ☺☺☺














    No comments:

    Post a Comment

    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...