Reputation: 61
I am adding data locally. And when I add, the amount of added data should show up in the badge component. But this happens only after switching to another page. And I need the data to be displayed immediately after adding.
How to do it?
quantity = 0;
ngOnInit() {
setTimeout( () => {
for (var i = 0; i < this.order.list.length; i++) {
this.quantity += this.order.list[i].quantity
}
}, 1000)
}
Upvotes: 0
Views: 106
Reputation: 1041
Try This,
import { Component, ElementRef, OnInit, ViewChild, ChangeDetectorRef, ViewRef } from '@angular/core';
constructor(private dtr: ChangeDetectorRef,){}
quantity = 0;
ngOnInit() {
setTimeout( () => {
for (var i = 0; i < this.order.list.length; i++) {
this.quantity += this.order.list[i].quantity
this.dtr.detectChanges();
}
}, 1000)
}
Upvotes: 0
Reputation: 700
You're initialising your data in the Component you've pasted a snippet of.
Components are able to share data (directly) by passing them to other Components (children) in their template - this is achieved by passing data to properties, in the child Components, annotated with a @Input
-decorator.
Passing the data the other way (from a child to its parent) can be done by emitting events. Here, a EventEmitter is declared in the child component, annotated with @Output
-decorator.
If you want to share data between Components without child / parent relationships - which could be Components loaded by the Angular Router
, you can hold the data in a @Service
-annotated class, that can be injected using Angular's Dependency Injection mechanism.
This is all explained (in great detail) in Angular's "Tour of Heroes" tutorial (which can be found here: https://angular.io/tutorial)
Upvotes: 1