Move Child Element Into a Different Container

Issue

I’m working within an Angular app (v10). I have a sharable component that will use the content given (ng-content). This content will likely be a list of items (divs, buttons, etc.)

I want to add logic that will move the last child of a container into a different container under certain circumstances (basically, if the width is too narrow, I’m going to move the items to another location). I have logic set up that will store the last item in an array and remove it from the original container. But I don’t know how to add this element to the new container.
I’ve tried to use ‘innerHTML’, but that shows object text instead of an HTML element.
I’ve tried to set the children of the new container to the movedItems (either by pushing or setting it to a new object), which didn’t work.
Not sure what else to try.

Here’s a quick stackblitz I whipped up: https://stackblitz.com/edit/angular-ivy-ioqhhx?file=src/app/app.component.html

Solution

This is more of a traditional javascript solution and not something that is specific to Angular so I’m not sure if it’s exactly what your looking for:
https://stackblitz.com/edit/angular-ivy-hi3cfd?file=src%2Fapp%2Fapp.component.ts. If anyone else has another solution that could utilize some kind of built-in Angular tool I would love to hear it too.

moveLastItem() {
    const lastIndex = this.startHereDiv.nativeElement.children.length - 1;
    const child = this.startHereDiv.nativeElement.children[lastIndex];
    this.moveHereDiv.nativeElement.appendChild(child);
  }

Oh and just in case if you’re wondering why your original code does not work, it is because this.startHereDiv.nativeElement.children[lastIndex] give you the object presentation of the element but [innerHTML] is expecting a raw string presentation of the element, here an example, you can check the console log to see what I meant. If you still want to go with the [innerHTML] solution, you will also have to by pass angular dom sanitizer as shown: https://stackblitz.com/edit/angular-ivy-c7ylm1?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

Answered By – Nam

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.