Built-in

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:

Common built-in structural directivesDetails

Conditionally creates or disposes of subviews from the template.

Repeat a node for each item in a list.

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']
})
export class NgIfExampleComponent {
  // Property to control the visibility of the message
  isMessageVisible: boolean = false;

  // Method to toggle the message visibility
  toggleMessage() {
    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:

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

3. Component CSS (Optional):

You can include some CSS for styling, but it is not necessary for this example.

CSS:

/* ngif-example.component.css */
button {
  margin: 10px;
  padding: 10px;
  font-size: 16px;
}

div {
  margin: 10px;
  padding: 10px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
}

p {
  font-size: 18px;
  color: #333;
}

Result:

  • Initial State: The message is not displayed because isMessageVisible is initially set to false.

Rendered HTML:

Initially:

<button>Show Message</button>
  • 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":

<button>Hide Message</button>
<div>
  <p>This message is conditionally displayed based on the value of isMessageVisible.</p>
</div>

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):

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());
    }
  }
}

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:

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

3. Component CSS (Optional):

You can include some CSS for styling, but it’s not essential for this example.

CSS:

/* ngfor-example.component.css */
input {
  margin: 10px;
  padding: 5px;
  font-size: 16px;
}

button {
  margin: 10px;
  padding: 10px;
  font-size: 16px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 5px 0;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
}

Result:

  • Initial State: The list will display the initial items: "Apple", "Banana", and "Cherry".

Rendered HTML:

Initially:

<input placeholder="Enter a new item" />
<button>Add Item</button>
<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>
  • 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":

<input value="Orange" />
<button>Add Item</button>
<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
  <li>Orange</li>
</ul>

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):

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
}

2. Component HTML:

Use *ngSwitch and *ngSwitchCase to conditionally display content based on the value of currentDay.

HTML:

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

3. Component CSS (Optional):

You can include some CSS for styling, but it’s not necessary for this example.

CSS:

/* ngswitch-example.component.css */
div {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ddd;
}

p {
  font-size: 18px;
  color: #333;
}

button {
  margin: 5px;
  padding: 10px;
  font-size: 16px;
}

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'):

<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>
  • 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:

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

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.

Last updated