Expanding a div with CSS and Angular: A comprehensive guide

For my project, I am working on a specific scenario:

When the user clicks on the "Animals" tile, it should expand while the other tiles replace it. Similarly, clicking on the "Plants" tile should expand it and reorder the other tiles.

===========1st View:============

https://i.sstatic.net/JvzEt.png

===========2nd View============== https://i.sstatic.net/WiY4f.png

The first page displays the tile view.

The second page displays the expanded div when a tile is clicked.

I need assistance in achieving this functionality. Below is a snippet of my code. I am able to show/hide the expanded tile, but I am struggling with hiding the clicked tile and reordering the other tiles. Any suggestions on how to accomplish this? I do not require expanding or contracting animations.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  showDiv:boolean = false;
  showDetails():void{
    this.showDiv = !this.showDiv;
  }
}

<div *ngIf="showDiv" style="width:450px;height:150px;border:2px solid black">
  Expanded div
</div>
<br/>
<div (click)="showDetails()" style="width:100px;height:100px;border:2px solid black;clear:both;float:left">
  tile 1
</div>
<div style="width:100px;height:100px;border:2px solid black;float:left;margin-left:10px">
  tile 2
</div>
<div style="width:100px;height:100px;border:2px solid black;float:left;margin-left:10px">
  tile 3
</div>

Answer №1

My recommendation would be to implement flexbox (CSS) for this particular task. Simply adjust the flexbox properties when the tiles are clicked.

Answer №2

One effective strategy is to incorporate Bootstrap classes such as col-lg-12 in combination with ngClass and a variable that updates upon clicking. By adjusting the variable, you can dynamically switch between bootstrap classes ranging from col-lg-3 to col-lg-12.

Answer №3

To tackle this issue, we can utilize the ViewChild decorator, but I believe we can simplify the solution without resorting to such a complex method. The key lies in streamlining the logic behind how tiles are displayed.

Initially, we can define the tiles within the component and store them in an array called tiles:

tiles = [
  { name: 'Animals' },
  { name: 'Plants'},
  { name: 'Organisms'},
];

Next, we can create a variable to represent the currently expanded tile and an array containing all tiles that are not expanded:

expandedTile = null;  
notExpandedTiles = this.tiles;  // initially, all tiles are not expanded

With this data in place, we can refactor the template using the *ngFor directive. Additionally, inline styles have been moved to a separate CSS file.

<div *ngIf="expandedTile" class="expanded-tile">
  {{expandedTile.name}}
</div>
<br/>
<div class="tiles">
  <div *ngFor="let tile of notExpandedTiles;" (click)="showDetails(tile)" class="tile">
    {{tile.name}}
  </div>
</div>

When a user clicks on a tile that is not expanded, it will be passed as an argument to the showDetails function, which will update the necessary data.

showDetails(clickedTile) {
  // set clickedTile as expandedTile
  this.expandedTile = clickedTile;
  // Update notExpandedTiles array to remove clickedTile
  this.notExpandedTiles = this.tiles.filter(tile => tile !== clickedTile);
}

CSS:

.tile, .expanded-tile {
  border: 2px solid black;
}

.tile {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin-right: 10px;
}

.expanded-tile {
  width: 450px;
  height: 150px;
}

Demo: https://stackblitz.com/edit/angular-8wekfm

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

Angular does not apply the ng-content class

I am facing an issue with my application where I have a layout that includes a div element with 2 ng-content tags. However, the classes are not being applied correctly. <div class="col-12 pr-1 pl-0 row m-0 p-0"> <ng-content class=&qu ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

I'm attempting to make it so that when users click on this link, it opens in a new tab instead of directing them away from my website. Unfortunately, using _blank

The link I have is currently opening in the same tab, but I want it to open in a new tab to keep users on my site. I've added target="_blank" to the code, but it's not working as expected. <BottomNavigation className={classes.root}> &l ...

Accelerate loading times of HTML files on Android apps

After clicking on an image, I want the corresponding HTML page to load instantly. However, there is a delay of a few seconds before the page actually appears. How can I reduce or eliminate this waiting time and ensure that the page loads as quickly as po ...

The functionality of the Bootstrap dropdown or radio input type is not functioning correctly

I'm currently utilizing electron([email protected]) along with bootstrap([email protected]). Whenever I attempt to incorporate a dropdown or other components from Bootstrap, they simply do not function. I am unsure of what mistake I might ha ...

Avoid automatic background resizing to match the full width of the header text

I've been trying to use CSS to style my <h1> element in a specific way, but it seems the default browser behavior is getting in the way: https://i.sstatic.net/oRR5N.png Despite my efforts, the browser continues to display it like this: https: ...

Make the table width 100%, but we don't want the central cell to be stretched

My table contains a central image cell that spans two rows: <table width="100%" style="text-align:center"> <tr> <td>Cell 1</td> <td>Cell 2</td> <td rowspan="2"><img src="http://www.skrenta.com/ima ...

How to Safely Swap Background Images on a Website Using CSS without Affecting the Body

How can I create a background similar to this one, but using an image instead of the blue background? Take a look at I noticed that resizing the browser window doesn't affect the background. What steps should I take to achieve this effect? ...

Python Automation with Selenium Web Scraping

I attempted to scrape the content of Crédit Suisse's page as an exercise. After creating this script, I encountered difficulties in retrieving the data. Initially, I suspected it may be due to an iframe issue or an AngularJS website structure, but u ...

Display the data in ngx-charts heat map

I have been utilizing ngx charts to display data in a Heat Map. The implementation is smooth without encountering any issues. View Working Example | Heat Map However, I am interested in displaying the values of each grid rather than just on mouse hover. ...

Utilize the canActivate method to decide when to display a specific hyperlink

I'm facing a challenge with my AuthGuard implementation using CanActivate to decide whether or not to display a link. Despite my efforts, I am unable to properly check the canActivate property of the Route. Here is the function I created: TypeScript ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...

Having trouble centering the links in the Bootstrap navbar?

I've been struggling to center the links/tabs on my Bootstrap navbar for days now and I just can't seem to get it right. I've gone through countless similar questions without any luck. Something must be off in my code or maybe I'm not t ...

"Exploring the Connection Between PHP, JSON, and

In my current class, we are collaborating on an android app project for our school. Due to the lack of physical meetings, I haven't had direct contact with some of my classmates. One member of the group has been responsible for programming the json an ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

Extract values from a deeply nested object while retaining the type information

How can I map all object values of the first obj while preserving the generic type for the Wrapped object? I attempted this using a mapped type, but encountered two issues: I'm struggling to represent a nested Object in the MapToWrappedType I can&ap ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

The function is not recognized in C# programming language

Whenever I try to trigger functions by clicking buttons, nothing seems to happen and an error message appears in the console. Uncaught ReferenceError: AddressInputSet is not defined at HTMLButtonElement.onclick I'm new to this and could use ...

Basic Jquery CSS style requests

Can you help me troubleshoot this issue? var hover = $('<img />').attr('src', hovers[i]).css('position', 'absolute') I'm having trouble getting th ...