0

I'm working with a small datagrid in Angular 2 and i have a question about parent/child relationships between components. I have two components: app-datagrid and app-add-item. The datagrid component, in his HTML, includes the app-add-item component, which is composed of a button and a modal. When clicked, the button displays the modal with a form to create a new item.

All the logic is isolated and nice: the app-add-item component creates and handles the form, sends the form data to the service and creates a new item. However, how can i update the datagrid once its child component has finished adding a new item?

Should the app-datagrid component listen for an event? Should it be passed as a dependency to the child? What's the proper way of doing this?

1 Answer 1

1

I think you could have the app-add-item component emit an @Output event to indicate an item has been added. Then have the app-datagrid bind to that event - something like this:

<app-data-grid #dataGrid> .. <app-add-item (itemAdded)="dataGrid.addNewItem($event)"></app-add-item> .. </app-data-grid> 
Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't this add a pretty direct dependency between the two? Shouldn't they be isolate?
What i mean is: why the add-item component needs to know that a datagrid component is expecting stuff from it?
The add-item component doesn't know what the datagrid is expecting - it just provides an output event indicating that something has been added. You could have a number of actions be bound to that event - e.g. add a row to the grid, display a message etc. None of these actions are defined in the add-item component.
There are a few ways for components to communicate but this is the simplest (at least for me) that would meet your requirements. The documentation for component communication describes this under the 'Parent listens for child event' section.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.