Interacting with Child Components in Angular2

There are lots of situations where we have to divide a component into several sub-components, resulting in a parent with N child components that somehow have to interact with the parent, like for example a menu component like this:

<menu-component>
   <menu-item [label]="'Item 1'"></menu-item>
   <menu-item [label]="'Item 2'"></menu-item>
   <menu-item [label]="'Item 3'"></menu-item>
   <menu-item [label]="'Item 4'"></menu-item>
   <menu-item [label]="'Item 5'"></menu-item>
</menu-component>

In this case the menu-component class must have access to every menu-item in order to completely render the component, that’s what I’m going to show you in this tutorial, but before we begin keep in mind that this is not a real menu component, it’s just an example I’m using to demonstrate how the components can interact.

Now let’s see how it works, here are the sources of both components:

MenuItemComponent

@Component({
  selector: 'menu-item',
  template: ``,
})
export class MenuItemComponent {
  @Input() label;
 
  constructor(menu: MenuComponent) {
    menu.items.push(this);
  }
}

MenuComponent

@Component({
  selector: 'menu-component',
  template: `
      <ul>
         <li *ngFor="let item of items">{{item.label}}</li>
      </ul>
  `
})
export class MenuComponent { 
  items: MenuItemComponent[] = [];
}

The parent iterates over a list of menu items in the template in order to display the label of each one of them in a li element, but as you can see the items array is empty and I’m not adding anything to it in this class, now if you take a look at the MenuItemComponent‘s constructor you’ll see that Angular2 makes things very easy for us by injecting the parent component, allowing each item to access the array in the parent and add itself to it.

That’s pretty much it guys, this was a very short tutorial but I hope it was helpful for you, just leave a comment if you have any doubts.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>