Summary: Trouble with detecting changes in an input property in Angular app
Currently, in my Angular (2+) application, I am attempting to create a progress bar to track the progress of an asynchronous task handled by a service using an Observable. The Observable sends numbers as data to indicate the percentage of completion of the task. There are three key components involved: The Service, ResultsComponent, and ProgressBarComponent (which is a child component of ResultsComponent). The flow of data goes like this:
- The Observable sends a number to ResultsComponent
- The ResultsComponent sets percentLoaded equal to this number
- ProgressBarComponent uses percentLoaded as an Input and should update the view accordingly
However, there seems to be an issue as the view is not updating as expected.
In ResultsComponent, the code snippet looks like this:
this.service.doTheTask()
.subscribe(
data => {
this.percentLoaded = data;
this.ref.detectChanges();
},
e => console.log('error:', e),
() => {
this.isLoading = false;
this.percentLoaded = 0;
}
);
By adding ref.detectChanges(), the OnChanges hook successfully triggers in ProgressBarComponent. Below you can find the code snippets for the Component and Template:
Component
export class ProgressBarComponent implements OnChanges {
@Input() percentLoaded = 0;
constructor() { }
ngOnChanges(changes) {
console.log('changes: ', changes);
}
}
Template
<div class="meter">
<div class="percent" [style.width.%]="percentLoaded"></div>
</div>
<p>{{percentLoaded}}% Loaded</p>
As seen above, I am simply logging the changes to investigate. It has been confirmed that ngOnChanges is triggering and the values are correct. According to the information I've gone through, "Once changes are detected, the view will automatically update," so I'm unsure about what else could be done.
Any suggestions or advice?