I have a parent angular component that displays children components with ngFor directive. Each child acts as an individual window within the parent and their position can be rearranged by CdkDrag. And I also created a small "X" button on the right top corner to close the child component. And when I hit "x" button to close one child with low index (e.g., 1 or 2 in the stackbliz example below), the other children are rearranged automatically. Is there a way to prevent such rearrangements and stay as is 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 stackbliz example
There're another approach, that I remember used in this SO
If we imagine a cdkDropList with "items" inside we can do some like
Yes a cdkDropList na be different that a list!
And some of .css
Stackblitz