I have few small divs having background color like red,yellow,pink etc which are coming from loop.On click of corresponding div a big div should show with same color which is working fine.But my requirement is suppose if I click on red(small div) a big red div should appear again when I click yellow(small div) an yellow big div should appear on earlier div on replacing it.Now it is not replacing it is creating new div and toogle is happening.
app.component.html
<div *ngFor="let color of colors" class="color-div" [ngClass]="color" (click)="toggleBigDiv(color)">
{{color}}
<div class="big-div" *ngIf="shownDivs[color]" [ngClass]="color">
Big {{color}} Div
</div>
</div>
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
colors = ['red','yellow','pink','green'];
shownDivs:{ [key:string]:boolean } = {};
title = 'project';
toggleBigDiv(color:string){
this.shownDivs[color] = !this.shownDivs[color];
}
app.component.css
.red{
background-color: red;
}
.yellow{
background-color: yellow;
}
.pink{
background-color: pink;
}
.green{
background-color: green;
}
.big-div{
position: absolute;
left : 110px;
width:300px;
height:300px;
}
3
Answers
The best solution is to move the div outside the loop to prevent elements being created. Then on click, we can get the position of the click using event then set the top and left position.
Stackbltiz Demo
You can reset the object to blank, when a new click event occours. This will involve no HTML changes.
Stackblitz Demo
I guess next one will help:
you can move the big div out side the loop and have a new variable indicate the current color