The Angular overlay panel remains open consistently

I recently developed an Angular component similar to p-overlaypanel, but I'm facing an issue where it remains open for every item I click. What I actually want is for only one overlay panel to be clicked and shown at a time - if I click on another overlay panel, the previously opened one should be hidden.

For reference, you can check out the code in stackblitz here.

Below is the snippet of the code:

<div class="dropdown">

  <div  class="body">
    <ng-content select="[body]"></ng-content>
  </div>

  <div *ngIf="active" class="popup">
    <ng-content select="[popup]"></ng-content>
  </div>

</div>
.dropdown {
  position: relative;
  display: inline-block;
}

.popup {
  display: block;
  position: absolute;
  z-index: 1000;
}

export class OverlaypanelComponent implements OnInit {

  active = false;

  constructor() {

  }

  ngOnInit() {

  }
  
  @HostListener('document:click', ['$event']) clickedOutside($event) {
    this.active = false;
  }

  toggle($event) {
    $event.preventDefault();
    $event.stopPropagation();
    this.active = !this.active;
  }

  close() {
    this.active = false;
  }

}

Answer №1

To achieve this task, the child component (panel) must find a way to notify the parent when it is opened so that the parent can close other panels accordingly. For this purpose, the active property should be bound as an Input. This involves adding three things: an Input binding to indicate if the panel is active, an Input binding for panel identification, and an Output binding to signal when the panel is displayed:

@Input() active = false;
@Output() activeChanged = new EventEmitter();
@Input() index;

toggle($event) {
  $event.preventDefault();
  $event.stopPropagation();
  this.active = !this.active;
  if (this.active) {
    this.activeChanged.emit(this.index);
  }
}

The parent component needs to bind to these properties and handle the Output to update the bindings of other panels. This can easily be managed using an array or another data structure to store the panels.

panels = new Array(4).fill({ active: false });

closeOtherPopups(index) {
  this.panels = this.panels.map((panel, idx) => (
    { active: idx === index }
  ));
}

Check out the implementation here: https://stackblitz.com/edit/angular-u96ssk?file=src/app/app.component.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

Spin a sphere within a semicircle using html and css

I have been working on a project to animate a ball inside a crescent shape using HTML and CSS. You can check out my codepen here. However, I am facing an issue where the ball is currently stuck at the top of the crescent. I would greatly appreciate any as ...

What is the best way to save Arabic text in a MySQL database from an HTML form using PHP?

I've been searching extensively, but have had no luck! >> Following the PHP connection I included: mysql_set_charset('utf8', $conn); >> The form input tag has the attribute: accept-charset="utf-8" >> I confirmed that the d ...

Tips for creating content with ellipsis after every 5 characters

I am new to coding and I need some assistance. I want to truncate text in my navigation bar if it exceeds 5 characters by displaying the first 5 characters followed by an ellipsis. This is to prevent display issues in my nav menu. For example: Input: T ...

Is there a way to identify and retrieve both the initial and final elements in React?

Having an issue with logging in and need to retrieve the first and last element: Below is my array of objects: 0: pointAmountMax: 99999 pointAmountMin: 1075 rateCode: ['INAINOW'] roomPoolCode: "ZZAO" [[Prototype]]: Object 1: pointAmoun ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

"Need help solving the issue of generating a random number for a Firebase DB column after adding a new user

Whenever I add a new user using JavaScript, it generates a random number below the Admins column like this. However, I want to adjust this so that it appears as shown in these tables, displaying the username value. If anyone can help me modify the code acc ...

HTML files do not inherit from other HTML files

I am venturing into the world of VSCode for the first time to create a web application. Starting with the basics, I have an index.html page with a simple "Hello, world!" message. Additionally, I have developed a layout.html file that contains code for a na ...

Using PHP to upload a lone image file to an FTP server

I'm feeling frustrated trying to achieve a simple task. I just want to create an HTML form and use PHP to upload the selected file to a specific directory on an FTP server, but for some reason it's not working as expected. Here is the HTML form ...

Access information from your own API endpoint and incorporate it with an interface

Trying to retrieve the json-data from an api-server but encountering difficulties adding it to the variable. The error received is: Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, p ...

What is the best way to make a div pull its background image directly from the internet instead of using the cached version?

Running relevant Javascript every fifteen minutes to fetch the appropriate image from the internet: document.getElementById('weatherbug').style.background = "url('http://tinyurl.com/jwltx5s') repeat scroll -1px -24px transparent"; The ...

Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called? globalvars.ts; httpgetmethod(url:string) { var veri; var headers = new Headers(); headers.append(' ...

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...

Angular nested router causing an infinite loop

I am currently working on creating a basic webpage layout consisting of a header, menu, and content div. My goal is to have the content div populate with the corresponding page when a user clicks on a link in the menu. Currently, I just want this common la ...

Step-by-step guide for embedding a Big Commerce website into an iframe

Can a website be opened inside an iframe? If not, is it possible to display a message like 'page not found' or 'this website does not allow data fetching in iframes'? <!DOCTYPE html> <html> <body> <h1>Using the ...

Tips for including background pictures in the jumbotron using bootstrap

I've recently delved into bootstrap just a couple of days ago. Now, I'm encountering an issue where I can't seem to add a background image to my entire webpage or even the jumbotron specifically. I've attempted to directly input the pa ...

Customizing Material-UI styles with type overrides

Is there a way to change the MuiIconButton-root class when using MuiSvgIcon with the fontSizeSmall attribute? import React from 'react' import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; const theme = createMuiT ...

The index "visible" in $_POST has been flagged as not defined

I am currently developing a PHP project and have a form that needs to be submitted. The form code is as follows: <h2>Create Subject</h2> <form action="create_subject.php" method="post"> <p>Subject name: <inp ...

Incorporating Kekule.js into a TypeScript-based React application

Greetings, community! I've created a React app designed to help individuals in the field of chemistry share their work. To facilitate this, I came across a library called Kekule.js Here is the link Utilizing TypeScript poses a challenge as it requir ...