6. Directives_ ngIf and ngFor

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives. Directives are classes that add additional behavior to elements in your Angular applications. Angular has some built-in directives like NgIf and NgFor.

a. NgIf

NgIf is a structural directive that conditionally includes a template based on the value of an expression. When the value of the expression is false, Angular removes an element and its descendants from the DOM. Angular then disposes of their components, which frees up memory and resources.

To add or remove an element, bind *ngIf to a condition expression such as isValid in the following example.

<p *ngIf=”isValid”>Hello</p>

When the isValid expression returns a truthy value, NgIf adds the p element to the DOM. When the expression is falsy, NgIf removes the p element from the DOM and disposes of the component and all of its sub-components.

b. NgFor

NgFor is a structural directive that renders a template for each item in a collection which must be an iterable such as an array. You can use the NgFor directive to present a list of items.

To demonstrate the usage of ngFor, let us initialize an array in the component class as follows

export class ExampleComponent {

  courses = [‘HTML’, ‘CSS’, ‘JS’, ‘Angular’];

}

  1. Define a block of HTML that determines how Angular renders a single item.
  2. To list your items, assign the short hand let course of courses to *ngFor.

This will generate elements as follows:

<div>

   <p>HTML</p>

</div>

<div>

   <p>CSS</p>

</div>

<div>

   <p>JS</p>

</div>

<div>

   <p>Angular</p>

</div>

Quiz:

What is an Angular directive?

a) A class that adds additional behavior to elements in Angular

b) A programming language used in Angular

c) A component that handles HTTP requests

d) A feature that manages routing in Angular

Which directive is used to conditionally render elements?

a) ngIf

b) ngFor

c) ngSwitch

d) ngClass

What does the ngFor directive do?

a) Iterates over a collection and creates a template for each item

b) Conditionally renders elements based on a boolean expression

c) Adds or removes an element from the DOM

d) Updates the CSS classes of an element based on a condition

Which directive is used to handle element repetition in Angular?

a) ngRepeat

b) ngLoop

c) ngFor

d) ngIterate

Answer: c

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *