I have a parent Angular component that showcases multiple children components using the ngFor directive. Each child functions as its own window within the parent container and can be repositioned using CdkDrag. Additionally, I have added a small "X" button in the top right corner of each child component to allow for closing. However, when I close a child with a lower index (such as 1 or 2), the remaining children are automatically rearranged. Is there a way to prevent this rearrangement and keep the layout consistent when closing any child window?
Child Component
@Input('target') target: string = '';
@Input('index') index: string = '';
@Output() onClose: EventEmitter<number> = new EventEmitter();
closeModal() {
const i: number = +this.index;
this.onClose.emit(i);
}
Child Template
<div class="example-box" cdkDrag>
{{target}}
<button class="CloseButton" (click)="closeModal()">X</button>
</div>
Child CSS
.example-box {
width: 100px;
height: 100px;
border: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
display: flex;
justify-content: center;
position: relative;
resize: both;
}
.CloseButton {
position: absolute;
top: 10px;
right: 10px;
}
Parent Component
names: string[] = ['1', '2', '3'];
modalClosed(id: any) {
this.names.splice(id, 1);
console.log(id);
}
Parent Template
<div class="ParentMain">
<child-comp
*ngFor="let name of names ; index as i"
(onClose)="modalClosed($event)"
target="{{name}}"
index="{{i}}"
>
</child-comp>
</div>
Parent CSS
.ParentMain {
display: flex;
}
Complete StackBlitz Example