How to hide div in Angular 17?

Mastering Visibility: Hiding DIV Elements in Angular

Introduction: Controlling UI Components in Angular

Ayyaz Zafar
2 min readNov 16, 2023

--

In this tutorial, we delve into various methods of hiding a div element in an Angular application. These techniques are crucial for controlling the visibility of UI components based on specific conditions or user interactions. Before we start, ensure you have a basic understanding of Angular and that Angular CLI is installed on your computer.

Using the “if” Condition to Hide Elements

In Angular 17, we use a new syntax for the if condition. Suppose you want to hide a div based on a condition, like a user not being logged in. Here's how you do it:

  1. In your Angular project, create a property in your component:
isLoggedIn = false;

2. In your HTML, use the if condition with this property:

<div *ngIf="isLoggedIn">   
<h1>Welcome User</h1>
</div>

2. This if condition removes the element from the DOM when the condition is false. The h1 tag, for instance, will only be displayed when isLoggedIn is true.

Hiding Elements with CSS Class Binding

For scenarios where you want to hide an element without removing it from the DOM, use CSS class binding:

  1. In your component’s CSS file, add a .hidden class:
.hidden {   
display: none;
}
  1. Use Angular class binding in your HTML:
<h1 [class.hidden]="!isLoggedIn">Welcome User</h1>

This method hides the element visually but keeps it in the DOM.

Dynamic Styling with NG Style

For more dynamic controls, such as responding to user actions or application state changes, use the ngStyle directive:

  1. Remove the previous methods and use ngStyle in your HTML:
<h1 [ngStyle]="{ 'display': isLoggedIn ? 'block' : 'none' }">   Welcome User </h1>

2. This directive applies inline styles based on the isLoggedIn property. It’s a versatile way to apply various styles conditionally.

--

--