Order Dynamic Components Inside an Angular 2 ViewContainer

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

By default, when you generate components, they will simply be added to the page in order, one after another. Angular 2 provides methods on the ViewContainer that allow you to reorder components once they’ve been created and provide the order that you want.

[00:00] It's important to understand that this view container ref that we're getting off of this div, so this guy here, is the one we're attaching all of these components to, but when you look at it in the DOM...Let's go ahead and inspect this here, you'll see that the container is here and the elements are beneath it.

[00:22] They're not inside of it, so they are siblings. It's not a parent child relationship. You could think about if they did try to be placed inside of it, you would lose track of the order of the elements inside of the container, and it would be hard to manage all of that.

[00:35] Let's go ahead and manage the order of these, using this create component method. Right now, this is the last component, because it's simply being created last, but if I put in two here, and say I'm third, you'll see that this is now the third value.

[00:54] You have one, two, three, starting from a zero-based index, zero, one, two, and that makes this one, the third one being created, thus making it the third one underneath, or the third sibling next to that div that we marked as our container.

[01:11] You can do this at any time as well. If you just...we'll create a button here. We'll say add component, and just on click, we'll go ahead and say on click. In this on click, I can just on click and do this same thing.

[01:33] I'll just go copy paste, and the widget factory is the resolved widget three, just copy and paste. You could keep track of a reference to this. I'm just going to do it in line, here.

[01:45] I'll go ahead and put this at the fourth position, so I'll say I'm fourth. You'll see when I save and I come and click this button up here, so click, you'll see that it adds it at the fourth position, and pushed everything else down, so I can keep clicking.

[02:02] It's adding more and pushing every other component down. From here, you do have complete control of the order.