Move and Delete Angular 2 Components After Creation

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

After the original order is set, you can still leverage methods on the Angular 2 ViewContainer to reorder the components. This is especially helpful when you want an event to trigger layout changes from your generated components.

[00:00] Instead of making a new component every time we click add component, let's instead move this third one around within the list of our current components. I'll just delete everything inside of on click. I'm going to say move component, just so that's explicit there.

[00:16] Then I'll need a reference to widget ref, so I'll say this, this, and make sure we have declared it up here. Now we'll have access to this widget ref once it's created, and on click, you can get the container, and say move.

[00:36] This.widgetref. The important part to remember here is you're not actually moving the widget reference, you're moving the view reference that lives inside of the created template. This is something called host view on the widget reference, like there's an instance of the component on the widget reference, and there's the host view, the rendered template, of the widget reference.

[00:59] Let's move that to the third position. I'll hit save, or the fourth position, since it's zero-based. Hit save, and then when this renders, I'll click, and you'll see this one moved from here down to here. To have a bit more fun with this, I'll say const random index.

[01:19] This will just be math.random times the this.container.length. Just make sure to floor that, math.floor, so it'll round it down. We'll move it to a random index every time I click. This way, when I click on this button, this will start jumping around in the list to random positions.

[01:44] You can see it moving, and moving, and moving anywhere in between zero, one, two, three, four, five, six, seven, eight. Clicking, clicking, clicking, and moving it around. Again, there is an API on the container itself, the view container ref that we have from here, that allows you to move these elements.

[02:04] Finally, we can either insert a new element, which would work the same way, or an obvious one you'll want to note is detach. You detach by index. I'll just say detach the one at two. I'll hit save, and you'll say, "There's my component, my rendered element, and it's gone."