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
2
Answers
It’s belonged to how you handle the items position when drag and drop, you need to save item position after onDragEnded event, you can see example here:
If you want to preserve the position of each dialogue after the close button is pressed, then there are a number of ways to do it. The simplest is to hide the dialogue when the button is clicked instead of removing them from the template.
Here’s an example of doing just that: https://stackblitz.com/edit/angular-pqf4je-aatkjg?file=src%2Fapp%2Fchild-comp.html
In the above, clicking the dialogue causes the item to disappear but the remaining items shouldn’t move because the item is in fact still there, it’s just been set to opacity: 0.
A slightly more advanced approach that doesn’t result in lots of invisible components on the screen would be to use CSS to position the items in specific positions – that way they won’t move when one is removed.