Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, and manipulating the host elements to which they are attached.
This section introduces the most common built-in structural directives:
A set of directives that switch among alternative views.
NgIf
1. Component TypeScript:
Define the property and method to toggle the visibility of the message.
TypeScript (Component):
import{Component}from'@angular/core';@Component({selector:'app-ngif-example',templateUrl:'./ngif-example.component.html',styleUrls: ['./ngif-example.component.css']})exportclassNgIfExampleComponent{ // Property to control the visibility of the message isMessageVisible:boolean=false; // Method to toggle the message visibilitytoggleMessage(){this.isMessageVisible =!this.isMessageVisible;}}
2. Component HTML:
Use *ngIf to conditionally display the message based on the isMessageVisible property. Add a button to toggle this property.
HTML:
3. Component CSS (Optional):
You can include some CSS for styling, but it is not necessary for this example.
CSS:
Result:
Initial State: The message is not displayed because isMessageVisible is initially set to false.
Rendered HTML:
Initially:
Button Clicks: Clicking the button will toggle the isMessageVisible property. When isMessageVisible is true, the message will be shown; when isMessageVisible is false, the message will be hidden.
After Interaction:
After clicking "Show Message":
Clicking "Hide Message" will hide the message again.
Summary
*ngIf conditionally includes or excludes elements from the DOM based on a boolean condition.
The button toggles the value of isMessageVisible, demonstrating how *ngIf can be used to manage element visibility dynamically.
User interactions with the button update the component state and affect the display of the message.
NgFor
1. Component TypeScript:
Define the list of items and a method to add a new item.
TypeScript (Component):
2. Component HTML:
Use *ngFor to iterate over the list of items and display each item. Include an input field and button to add new items.
HTML:
3. Component CSS (Optional):
You can include some CSS for styling, but it’s not essential for this example.
CSS:
Result:
Initial State: The list will display the initial items: "Apple", "Banana", and "Cherry".
Rendered HTML:
Initially:
Adding Items: Typing a new item in the input field and clicking "Add Item" will add the new item to the list.
After Interaction:
For example, after typing "Orange" and clicking "Add Item":
Summary
*ngFor is used to iterate over an array or collection and create a template for each item.
The input field and button allow users to add new items dynamically to the list.
User interactions with the input and button show how *ngFor can dynamically update the view based on the component’s state.
NgSwitch
1. Component TypeScript:
Define the currentDay property and options for the days of the week.
TypeScript (Component):
2. Component HTML:
Use *ngSwitch and *ngSwitchCase to conditionally display content based on the value of currentDay.
HTML:
3. Component CSS (Optional):
You can include some CSS for styling, but it’s not necessary for this example.
CSS:
Result:
Initial State: The message corresponding to the initial value of currentDay (e.g., 'Monday') will be displayed.
Rendered HTML:
Initially (with currentDay set to 'Monday'):
Button Clicks: Clicking a button will update the currentDay property, and the content inside the ngSwitch container will change based on the new value.
After Interaction:
For example, after clicking the "Friday" button:
Summary
*ngSwitch is used to conditionally display content based on a value.
*ngSwitchCase specifies the content to display for each possible value.
*ngSwitchDefault provides fallback content when no cases match.
User interactions with the buttons demonstrate how *ngSwitch dynamically updates the view based on the currentDay value.
<!-- Button to toggle the message visibility -->
<button (click)="toggleMessage()">
{{ isMessageVisible ? 'Hide' : 'Show' }} Message
</button>
<!-- Conditional message display -->
<div *ngIf="isMessageVisible">
<p>This message is conditionally displayed based on the value of isMessageVisible.</p>
</div>
<button>Hide Message</button>
<div>
<p>This message is conditionally displayed based on the value of isMessageVisible.</p>
</div>
import { Component } from '@angular/core';
@Component({
selector: 'app-ngfor-example',
templateUrl: './ngfor-example.component.html',
styleUrls: ['./ngfor-example.component.css']
})
export class NgForExampleComponent {
// Define a list of items
items: string[] = ['Apple', 'Banana', 'Cherry'];
// Method to add a new item to the list
addItem(newItem: string) {
if (newItem.trim()) {
this.items.push(newItem.trim());
}
}
}
<!-- Input field for adding new items -->
<input #newItem placeholder="Enter a new item" />
<!-- Button to add a new item -->
<button (click)="addItem(newItem.value); newItem.value=''">
Add Item
</button>
<!-- Display the list of items -->
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
typescriptCopy codeimport { Component } from '@angular/core';
@Component({
selector: 'app-ngswitch-example',
templateUrl: './ngswitch-example.component.html',
styleUrls: ['./ngswitch-example.component.css']
})
export class NgSwitchExampleComponent {
// Define the current day
currentDay: string = 'Monday'; // Change this value to see different results
}
<!-- Container with *ngSwitch directive -->
<div [ngSwitch]="currentDay">
<!-- Content for Monday -->
<p *ngSwitchCase="'Monday'">Start of the work week! Let's get productive.</p>
<!-- Content for Tuesday -->
<p *ngSwitchCase="'Tuesday'">It's Tuesday! Keep up the great work.</p>
<!-- Content for Wednesday -->
<p *ngSwitchCase="'Wednesday'">Midweek! You’re halfway through the week.</p>
<!-- Content for Thursday -->
<p *ngSwitchCase="'Thursday'">Just one more day until Friday!</p>
<!-- Content for Friday -->
<p *ngSwitchCase="'Friday'">Happy Friday! The weekend is almost here.</p>
<!-- Default content for other days -->
<p *ngSwitchDefault>Not a valid day! Please select a valid day of the week.</p>
</div>
<!-- Buttons to change the currentDay property -->
<button (click)="currentDay = 'Monday'">Monday</button>
<button (click)="currentDay = 'Tuesday'">Tuesday</button>
<button (click)="currentDay = 'Wednesday'">Wednesday</button>
<button (click)="currentDay = 'Thursday'">Thursday</button>
<button (click)="currentDay = 'Friday'">Friday</button>
<button (click)="currentDay = 'Saturday'">Saturday</button>
<button (click)="currentDay = 'Sunday'">Sunday</button>
<div>
<p>Start of the work week! Let's get productive.</p>
</div>
<button>Monday</button>
<button>Tuesday</button>
<button>Wednesday</button>
<button>Thursday</button>
<button>Friday</button>
<button>Saturday</button>
<button>Sunday</button>
<div>
<p>Happy Friday! The weekend is almost here.</p>
</div>
<button>Monday</button>
<button>Tuesday</button>
<button>Wednesday</button>
<button>Thursday</button>
<button>Friday</button>
<button>Saturday</button>
<button>Sunday</button>