Skip to main content

ngIf

ngIf is another important structural directive in Angular. It is used to conditionally add or remove an element from the DOM based on a specified condition. This directive plays a crucial role in controlling what parts of your application are visible to the user at any given time.

Basic Usage

The syntax for ngIf is *ngIf="expression", where expression is a JavaScript-like expression that evaluates to a Boolean. If the expression evaluates to true, Angular will add the element to the DOM. If it evaluates to false, Angular will remove the element from the DOM.

Example:

@Component({
selector: 'app-example',
template: `
<p *ngIf="showParagraph">This paragraph is conditionally rendered</p>
<button (click)="showParagraph = !showParagraph">Toggle Paragraph</button>
`
})
export class ExampleComponent {
showParagraph = true;
}

In this example, the paragraph will only be displayed if showParagraph is true. Clicking the button toggles the value of showParagraph, thus showing or hiding the paragraph.

Key Features and Considerations

  1. Removing Elements from the DOM:

    • Unlike CSS-based hiding (using display: none;), ngIf completely removes the element from the DOM when the condition is false, not just hiding it. This also means any component lifecycle hooks (like ngOnInit or ngOnDestroy) will be triggered if those lifecycle events are defined in the component.
  2. Performance Considerations:

    • Since ngIf adds and removes elements from the DOM, it can have performance implications, especially for large elements or complex component trees. Use it judiciously to optimize performance.
  3. Else Clause:

    • ngIf can be combined with an else clause to display an alternative view when the ngIf condition is false.
    • Use a template reference variable to indicate the alternative template.
    <div *ngIf="condition; else elseTemplate">Content to render when condition is true.</div>
    <ng-template #elseTemplate>Alternative content.</ng-template>
  4. As a Structural Directive:

    • Remember that ngIf is a structural directive, so it changes the structure of the DOM. This is different from attribute directives, which only change the behavior or appearance of an element.

More Examples

Below are few more examples hat are used with different possible use cases.

Basic Use of ngIf

  1. Simple Conditional Display: Show a message only if a condition is true.

    <p *ngIf="isLoggedIn">Welcome back, user!</p>

    Here, the paragraph is only rendered if isLoggedIn evaluates to true.

Using ngIf with an Else Block

  1. Conditional Display with Else Clause: Display one of two templates based on a condition.

    <div *ngIf="isLoading; else notLoading">
    Loading...
    </div>
    <ng-template #notLoading>
    <div>Data Loaded</div>
    </ng-template>

    In this example, "Loading..." is displayed if isLoading is true. Otherwise, "Data Loaded" is shown.

Using ngIf with Then and Else Blocks

  1. Conditional Display with Then and Else: Define both the then and else blocks explicitly.

    <div *ngIf="user; then loggedIn else notLoggedIn"></div>
    <ng-template #loggedIn><p>Welcome, {{ user.name }}!</p></ng-template>
    <ng-template #notLoggedIn><p>Please log in.</p></ng-template>

    This shows a personalized message if user is defined, and a login prompt if not.

Combining ngIf with Other Directives

  1. With ngFor for Conditional Lists: Conditionally render a list of items.

    <div *ngIf="items.length; else noItems">
    <ul>
    <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    </div>
    <ng-template #noItems><p>No items found.</p></ng-template>

    This displays a list if items is not empty, and a message if it is.

Using ngIf for Feature Toggling

  1. Feature Toggle: Enable or disable features based on a toggle.

    <div *ngIf="featureEnabled">
    <app-new-feature></app-new-feature>
    </div>

    This only includes the app-new-feature component in the DOM if featureEnabled is true.

Using ngIf with Functions

  1. With Function Calls: Execute a method to determine if the element should be displayed.

    <p *ngIf="shouldShowMessage()">This message is conditionally displayed.</p>

    In this case, shouldShowMessage() is a method in the component that returns a boolean.

Using ngIf for Error Messages

  1. Displaying Error Messages: Show an error message based on validation.

    <div *ngIf="form.hasError('required', 'email')">
    Email is required.
    </div>

Best Practices

  • Use for Conditional Rendering: Ideal for scenarios where you need to conditionally render entire sections of the UI.
  • Minimize DOM Manipulations: Be cautious of frequently toggling elements in and out of the DOM, as it can lead to performance issues.
  • Combine with Other Directives: Use in conjunction with directives like ngFor for more dynamic and responsive UIs.

Use Cases

  • Feature Toggles: Show or hide features based on certain conditions (like user permissions).
  • Dynamic Content: Render parts of the page only when needed, such as displaying messages or warnings based on user actions.
  • Layout Changes: Altering the layout dynamically in response to user interactions or application state changes.

Conclusion

ngIf is a versatile and powerful directive in Angular for controlling the visibility of elements. It helps in creating a dynamic and interactive user experience by conditionally rendering parts of the application. Understanding its use and implications is fundamental for effective Angular development.