Saturday, August 16, 2025
0 comments

Master Angular 20 Components, Templates, and Directives: A Beginner’s Guide with Hands-On Examples and Troubleshooting (Part-2)

 


Templates & Directives in Angular 201. TemplatesTemplates in Angular define the UI of a component using HTML, enhanced with Angular-specific syntax for data binding, directives, and pipes. They are typically stored in a separate .html file (referenced via templateUrl) or inline using template in the @Component decorator.Example:
typescript
// src/app/components/user/user.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `<h2>Welcome, {{ name }}!</h2>`, // Inline template
  // OR
  // templateUrl: './user.component.html',
  standalone: true
})
export class UserComponent {
  name = 'John Doe';
}
Templates use Angular’s binding syntax ({{ }}, [], ()) and directives to make the UI dynamic.
2. Structural DirectivesStructural directives modify the DOM by adding, removing, or manipulating elements. They are prefixed with an asterisk (*). Common structural directives include:*a. ngIfConditionally includes or removes an element based on an expression.
html
<div *ngIf="isVisible">Show me!</div>
*b. ngForLoops over a collection to render elements.
html
<ul>
  <li *ngFor="let user of users">{{ user.name }}</li>
</ul>
*c. ngSwitchConditionally renders elements based on a switch expression.
html
<div [ngSwitch]="role">
  <p *ngSwitchCase="'admin'">Admin Dashboard</p>
  <p *ngSwitchCase="'user'">User Dashboard</p>
  <p *ngSwitchDefault>Guest Dashboard</p>
</div>
Explanation:
  • *ngIf: Shows/hides content based on a boolean.
  • *ngFor: Iterates over arrays or iterables.
  • *ngSwitch: Acts like a switch statement for conditional rendering.

3. Attribute DirectivesAttribute directives modify the behavior or appearance of an element. They are applied using square brackets ([]).a. [ngClass]Dynamically applies CSS classes based on conditions.
html
<div [ngClass]="{'active': isActive, 'error': hasError}">Styled Div</div>
b. [ngStyle]Dynamically sets inline styles.
html
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">Styled Text</div>
Explanation:
  • [ngClass]: Adds/removes classes based on object key-value pairs or an array.
  • [ngStyle]: Sets CSS properties dynamically.

4. PipesPipes transform data in templates for display (e.g., formatting dates, numbers, or strings). Angular provides built-in pipes like:a. Date PipeFormats dates.
html
<p>{{ today | date:'fullDate' }}</p> <!-- Output: Saturday, August 16, 2025 -->
b. Currency PipeFormats numbers as currency.
html
<p>{{ price | currency:'USD' }}</p> <!-- Output: $99.99 -->
c. UpperCase PipeConverts text to uppercase.
html
<p>{{ name | uppercase }}</p> <!-- Output: JOHN DOE -->
Explanation: Pipes are applied using the | operator and can take parameters (e.g., date:'fullDate').
5. Creating a Custom PipeCustom pipes allow you to define reusable data transformations. Use the Angular CLI to generate a pipe:
bash
ng g pipe pipes/filter
Example: A custom pipe to filter users by role.
typescript
// src/app/pipes/filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterByRole',
  standalone: true
})
export class FilterByRolePipe implements PipeTransform {
  transform(users: any[], role: string): any[] {
    if (!users || !role) return users;
    return users.filter(user => user.role === role);
  }
}
Usage in template:
html
<ul>
  <li *ngFor="let user of users | filterByRole:'admin'">{{ user.name }}</li>
</ul>
Explanation: The pipe filters an array of users to show only those with the specified role.
6. Template Reference Variables (#var)Template reference variables allow you to reference DOM elements or components in the template using a # prefix.Example:
html
<input #nameInput placeholder="Enter name" />
<button (click)="logName(nameInput.value)">Log Name</button>
typescript
// Component
logName(value: string) {
  console.log('Input value:', value);
}
Explanation: #nameInput references the <input> element, and its value is accessed in the component.
Hands-On Project: Build a Dynamic Admin Users ListLet’s extend the blog post project to create a dynamic Admin users list using *ngFor, [ngClass], pipes, and template reference variables. We’ll enhance the AdminComponent to display a list of users with conditional styling and filtering.Step 1: Update the ProjectAssuming you have the project from the previous response (angular-components-demo), ensure it’s running:
bash
ng serve
If you encountered the TS2305 error, confirm main.ts and app.component.ts are set up as follows:
typescript
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, {
  providers: []
}).catch(err => console.error(err));
typescript
// src/app/app.component.ts
import { Component } from '@angular/core';
import { UserComponent } from './components/user/user.component';
import { AdminComponent } from './components/admin/admin.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  standalone: true,
  imports: [UserComponent, AdminComponent]
})
export class AppComponent {}
html
<!-- src/app/app.component.html -->
<app-user></app-user>
<app-admin></app-admin>
Step 2: Generate a Custom PipeRun:
bash
ng g pipe pipes/filter-by-role
This creates src/app/pipes/filter-by-role.pipe.ts.Step 3: Update AdminComponentModify the AdminComponent to display a dynamic list of admin users with filtering, styling, and template reference variables.
typescript
// src/app/components/admin/admin.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterByRolePipe } from '../../pipes/filter-by起身

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css'],
  standalone: true,
  imports: [FormsModule, FilterByRolePipe]
})
export class AdminComponent implements OnInit, OnDestroy {
  users = [
    { name: 'Alice', roleId: 1, role: 'admin' },
    { name: 'Bob', roleId: 2, role: 'user' },
    { name: 'Charlie', roleId: 1, role: 'admin' },
    { name: 'David', roleId: 2, role: 'user' }
  ];
  filterRole = 'admin';
  isHighlighted = false;

  ngOnInit() {
    console.log('AdminComponent: Initialized');
  }

  ngOnDestroy() {
    console.log('AdminComponent: Destroyed');
  }

  toggleHighlight() {
    this.isHighlighted = !this.isHighlighted;
  }

  setFilterRole(role: string) {
    this.filterRole = role;
  }
}
html
<!-- src/app/components/admin/admin.component.html -->
<h2>Admin Users List</h2>
<div>
  <label>Filter by Role: </label>
  <select [(ngModel)]="filterRole" (change)="setFilterRole(filterRole)">
    <option value="all">All</option>
    <option value="admin">Admin</option>
    <option value="user">User</option>
  </select>
</div>
<button (click)="toggleHighlight()">Toggle Highlight</button>
<ul>
  <li *ngFor="let user of users | filterByRole:filterRole"
      [ngClass]="{'highlight': isHighlighted && user.roleId === 1}">
    {{ user.name | uppercase }} ({{ user.role }})
  </li>
</ul>
<input #searchInput placeholder="Search users" />
<button (click)="logSearch(searchInput.value)">Search</button>
css
/* src/app/components/admin/admin.component.css */
ul {
  list-style-type: none;
  padding: 0;
}
li {
  padding: 10px;
  margin: 5px 0;
  border: 1px solid #ccc;
}
.highlight {
  background-color: #e0f7fa;
}
Step 4: Implement the Custom Pipe
typescript
// src/app/pipes/filter-by-role.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterByRole',
  standalone: true
})
export class FilterByRolePipe implements PipeTransform {
  transform(users: any[], role: string): any[] {
    if (!users || role === 'all') return users;
    return users.filter(user => user.role === role);
  }
}
Step 5: Explanation of the Project
  • Dynamic List (*ngFor): The *ngFor directive loops through the users array to display the list.
  • Custom Pipe (filterByRole): Filters users based on the selected filterRole.
  • Attribute Directive ([ngClass]): Applies the highlight class to admin users (roleId === 1) when isHighlighted is true.
  • Template Reference Variable (#searchInput): Captures the search input value when the button is clicked.
  • UpperCase Pipe: Converts user names to uppercase.
  • Lifecycle Hooks: Logs component initialization and destruction.
  • FormsModule: Enables [(ngModel)] for the role filter dropdown.
Step 6: Test the Application
  1. Run ng serve and visit http://localhost:4200.
  2. Test the Admin users list:
    • Use the dropdown to filter by role (admin, user, or all).
    • Click the "Toggle Highlight" button to highlight admin users.
    • Enter text in the search input and click "Search" to see the console log.
  3. Check the console for lifecycle logs (ngOnInit, ngOnDestroy).

0 comments:

Featured Post

Master Angular 20 Basics: A Complete Beginner’s Guide with Examples and Best Practices

Welcome to the complete Angular 20 learning roadmap ! This series takes you step by step from basics to intermediate concepts , with hands...

Subscribe

 
Toggle Footer
Top