The Logic by IMG I'm facing an issue with updating child component variables in real-time. I attempted to use @Input, but it only gets initialized and doesn't change over time.
Parent Component
<div>
<h4>Рэйтынг : {{video.starRating}}</h4>
<star-rating
[rating]="video.starRating"
(ratingChanged)="onRatingChanged($event)">
</star-rating>
</div>
Child Component
@Component({
selector: 'star-rating',
templateUrl: 'app/shared/star-rating.component.html',
styleUrls:['app/shared/star-rating.component.css'],
inputs:['rating']
})
export class StarRatingComponent implements OnInit,OnChanges {
rating: number;
@Output() ratingChanged = new EventEmitter<number>();
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
for (let propName in changes) {
let changedProp = changes[propName];
if(changedProp == "rating"){
this.calcStarRating();
console.log("rating = "+this.rating);
console.log("ratingCurr = "+changedProp.currentValue);
console.log("ratingPrev = "+changedProp.previousValue);
}
}
}
onStarClicked(item: number) {
this.ratingChanged.emit(item + 1);
}
calcStarRating() {
...calc logic....
console.log(this.rating)
}
ngOnInit() {
this.calcStarRating();
}
}
The video is
export class Video{
videoId:string;
videoTitle:string;
price: number;
description: string;
starRating: number;
imageUrl: string;
}
Parent Logic
export class VideoDetailComponent implements OnInit ,OnDestroy{
video:Video;
private sub: Subscription;
ngOnInit() {
this.sub = this._routeParams.params.subscribe(params=>{
if(params && params['id']){
this.sub1 = this._vs.getItemById(params['id'])
.subscribe(t=>this.video = t);
}
});
}
onRatingChanged(rating:number){
if(this.video.starRating!=0){
this.video.starRating +=rating;
this.video.starRating /= 2;
}
else this.video.starRating = rating;
this.video.starRating = +this.video.starRating.toFixed(2);
this._vs.updateItem(this.video);
}
onBack(){
this.router.navigate(['/list']);
}
constructor(private _routeParams: ActivatedRoute,
private _vs:VideoService,
private router: Router) {
}
}
I have observed that when I log the rating, no changes occur. I tried incrementing/decrementing the value. The parent model changes, but those changes are not sent to the child using @Input. My question is how can I bind them in real-time? Is it possible with @Input or do I need to use Observables/Events, etc?
Thanks for Reading:)