1

Here is code showing the bug: https://stackblitz.com/edit/angular-gbn3kr

I am trying to dynamically update a total quantity field. I created a Quantity Component which is an input that takes in a number and stores that number. In my app component, I have an array of these Quantity Components. When I try QuantityComponent.getQuantity() from the app component, it is always returning 0 even though I know I am correctly setting the components quantity because the components quantities are correctly displaying.

I assume that this is because my QuantityComponent in the array is not being updated. Is my assumption right? How would you code this?

3
  • you are instantiate the component again inside your service thats why quantity gets 0 Commented Jul 8, 2018 at 15:05
  • why are you set the this.totalQuantity = 0; inside the keyup event method that's why you are getting zero Commented Jul 8, 2018 at 15:10
  • You could try using event emitters, as they may simplify some of your code. Commented Jul 8, 2018 at 15:17

1 Answer 1

1

It is because your are creating new object of Quantity in your service. And in the View of App, you are Initiating two other independent instances of quantity. Whenever you use the component selector <quantity...>(like you did in app-component-html) angular instantiates the component. I have resolved it in this stackblitz

But you can enhance this by using EventEmitters which would better up the performance. I tried to stick with the idea that you had used that is why you would find a For-loop to get TOTAL value, but prefered way would be EventEmitters.

Sign up to request clarification or add additional context in comments.

5 Comments

Also, please note that you have used the 'keyup' event to track the value changes, working with the 'Up' and 'Down' arrows won't get a new value.
Given that, maybe just use [(ngModel)]="quantity" on your input instead, like this example: angular.io/tutorial/toh-pt1#edit-the-hero
Thank you! I did not expect that using the selector would instantiate a new component. I see that you got a reference to the QuantityComponents in the view with @ViewChildren(QuantityComponent). Is there a way to create the quantity components returned from the service in the view though?
You can refer to ViewContainerRef angular.io/api/core/ViewContainerRef. But may i know why would you want to do that?
I am just thinking of future applications when I may need to create a component in a service and then display it on my view. Thank you for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.