How to handle multiple events in the single component in Angular 4

0 votes
asked Sep 12, 2017 by rajashree-gr

I'm developing an UI layer for an application using angular 4, where I have a page layout as shown in below. I have to display the data in the respective table based on the search.

Right now i have the code to display the data in one html(records-list.component.html) that is a part of one component(records-list.component.ts). To display the results based on search, i'm using onSelect($event) event of the search boxes. In this case i will have two onSelect($event) events, 1 for search1 and 1 for search2.

My question is, what is the best way to handle the events in the components class?
1. Handle both the search box scenario's in single onSelect(event) method?
2. Do i have to split the code into 2 components(also 2 templates)? So that each component will take care of displaying each table data and events?
3. Create a method called search($event, 's1') in component and use some parameters to differentiate 2 searches and update the table based on the parameter?

This question may be silly or too simple, but i'm not able decide which way to choose. Please suggest me your ideas. Thanks.

enter image description here

1 Answer

+2 votes
answered Mar 10, 2018 by hogan

I think you're misunderstanding the difference between events and components a bit. So there is:

  1. The concept of smart/dumb components where you emit events. The usual syntax is something along <my-component (onLeftSelected)="performLeft($event)" (onLeftSelected)="performRight($event)"></my-component>.

In the 'my-component' you emit the event and define the handlers in the parent component.

!! BUT What I would likely do is split up left and right into separate components and declare the related methods in each without the use of emitting events.

So you'd have a left-component with a (click)="doSomething(data)" and a right-component with a (click)="doVeryImportantStuff(data)".

In that case the code would be decoupled and you can reuse either side in other parts in case you need it.

But as @AlexanderLeonov wrote you should first get an understanding of how you want to split that up first.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter