Angular 2 - Troubleshooting Issues with Nested Components and @Input Propagation

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:)

Answer №1

Functioning as intended, although it appears that there may be an issue with the if(changedProp == "rating"){...} line since you are comparing a string to an object.

To rectify this, you should update it to if(propName == "rating"){...}.

By making this adjustment, the dilemma should be resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using ngIf in Angular and eliminating components in Angular 6

Currently, I am faced with the challenge of removing the header and footer components in one specific component, but I'm unsure about how to proceed. In my approach, I consider the app component as the index.html component. Whenever I create a new com ...

Achieve triple condition handling using *ngIf else technique

My goal is to suggest nearby establishments to the user based on their location. I need to handle two scenarios: The user has allowed access to their geolocation The user has not granted access to their geolocation While checking if the geolocation ser ...

Angular tests are not reflecting HTML changes when there is a modification in the injected service

I'm currently testing a component that dynamically displays a button based on the user's login status. The user details are obtained from a service method, and the component uses a getter to access this information. Inside the component: get me ...

Angular trailing zero problem

There is a function that returns a number. Within this function, a string '1.10' is present, which is then converted to a number using the Number method. The output obtained is 1.1, but the desired output is 1.10. I have tried using methods lik ...

What could be causing Typescript Intellisense to not display Object extensions?

Let's take a look at this unique way to extend the Object type: interface Object { doSomething() : void; } Object.prototype.doSomething = function () { //perform some action here } With this modification, both of the following lines will c ...

Incorporating quotes into a unified npm script

I'm trying to merge two npm scripts into one, but the result is incorrect and causes issues with passing flags. I can't use the dotenv package, and using ampersands isn't solving the problem. Here's what I have in my package.json file ...

Replace i18next property type in React for language setting

We have decided to implement multilanguage support in our app and encountered an issue with function execution. const someFunction = (lang: string, url: string) => any If we mistakenly execute the function like this: someFunction('/some/url', ...

What causes an array of type `never[] & number[]` to be generated when using `Object.assign`?

Take a look at this code snippet: const arr = [1,2,3] const res1 = arr.slice() const res2 = Object.assign([],arr) When using arr.slice() to create a shallow clone, the resulting array res1 will have a type of number[], just like the original arr. However, ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Frozen objects in Typescript 2 behave in a variety of ways depending on their shape

Let's say I'm working with an object whose inner structure is unknown to me because I didn't create it. For instance, I have a reference to an object called attributes that contains HTML attributes. I then made a shallow copy of it and froze ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Retrieve a private property in spec.ts file of an Angular 6 application

In my Angular-6 service.ts file, I have a private variable that I am using. private tagSubject = new Subject<any>(); This variable is utilized in the following manner: sendNewTagMessage(message: string) { this.tagSubject.next({ text: message ...

Arrange objects in dropdown menu to line up

I'm currently working on a dropdown menu and I have a specific requirement – the menu should always be split into two columns and be able to span multiple lines. However, I've encountered an issue where the columns are not aligned properly, cau ...

"Enhancing Accessibility: Customizing Radio Button Labels in Angular Material for VoiceOver and Screen

I'm experiencing an issue with Angular Material's mat-radio-group and Apple's VoiceOver. When I test it, VoiceOver reads each radio label as "[the label] and one more item". For example, <mat-radio-button value="envelope">Envelope< ...

Issue with Readonly modifier not functioning as expected in Angular/Typescript

My goal is to create a component property that is read-only. However, I am facing an issue where the readonly modifier does not seem to have any effect. View example on stackblitz According to the documentation, once I initialize the cars property in the ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

How to transfer data between components in Angular 6 using a service

I'm facing an issue with passing data between the course-detail component and the course-play component. I tried using a shared service and BehaviorSubject, but it didn't work as expected. Strangely, there are no errors thrown, and the data remai ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...