Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5041

Input property not updating after event emitter - angular

I have 3 components using one inside other. Consider app, form-details, form-html. form-details is being used as child inside the app component. And form-html is being used as child component inside the form-details component.

From app component updating input property of form-details component to display or hide the form-html component. And also from form-html itself I am emitting an event to hide the form.

Here the issue is, once event is emitted from the form-html component to hide the form. If I try to open the form using button present in app component, input property in the form-details component is not updating instantly. We need to click button 2 times to display the form. Why it is happening?

As I am using ChangeDetectionStrategy.OnPush tried to resolve the issue with detectChanges method from changeDetectorRef, but didn't help me.

Please find the stackblitz from here to check the issue

Upvotes: 1

Views: 1108

Answers (2)

Alejandro Camba
Alejandro Camba

Reputation: 988

if you console log in your app.component you are going to see the problem:

displayForm() {
  console.log(!this.showForm)
  this.showForm = !this.showForm;
}

Nothing wrong with onPush change detection there, just that app.component doesn't know that showForm is changing because he is never getting the changes from details.component so it continues with it's normal flow: true -> false -> true -> etc ...

Implementing a new EventEmitter in details.component and catch the event in your app.component would do, or a shared service like andriusain said

Upvotes: 2

andriusain
andriusain

Reputation: 1207

Rather than using event emitters across components I suggest having a service that you inject into the components and where you just set and read properties from those components. In this way you can have your components devoid of business logic and handle that in the service. This is a better practice because you avoid having to rely in events to enable communication across components. It is a better programming pattern because it enables more reusability at less performance cost, and you are able to keep the business logic in one place making it easier to figure out what is going on in your application. If you had 100 components and each of those contained business logic it can become really taxing to maintain and figure out what is going on in your application.

Upvotes: 2

Related Questions