How to rerender Angular Component?

63 Views Asked by At

I have an issue with that Angular do not update @ViewChildren field. In component I have the following html view:

    <audio-player #audioPlayer
                  ...>
    </audio-player>

and the following code:

export class CustomDetailsComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
    ...
    @Input() customDetails: <Type>;

    @ViewChildren('audioPlayer') audioPlayers!: QueryList<AudioPlayerComponent>;
    ...
}

After update of main field customDetails of CustomDetailsComponent audioPlayers still is not updated. audioPlayers depends on number of audio files in customDetails component.

Is there a way to rerender CustomDetailsComponent completely ? Because for me it looks like that @ViewChildren('audioPlayer') calculated only once at component creation ...

2

There are 2 best solutions below

0
Denis Kotov On BEST ANSWER

What actually helped me is the following code:

export class CustomDetailsComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
    ...
    _customDetails!: <Type>;

    @Input({ required: true })
    set customDetails(value: <Type>) {
      this._customDetails = value;
      this.cdr.detectChanges();
    }

    get customDetails() {
      return this._customDetails;
    }


    @ViewChildren('audioPlayer') audioPlayers!: QueryList<AudioPlayerComponent>;
    ...
}

Because audioPlayers depends on number of components in customDetails, I decided to add setter for customDetails and run cdr for changes detection, and it helped !!

Of, this Angular dependency management in Angular is not so intuitive, most time it detects changes, but sometimes not, and you fight with it :)

0
Mr Antic On

If customDetails is an object type,it will not set off change detection because of its mutability. Make sure you're passing the values correctly in that case with {...passedObject}, to make it an immutable copy and not a pointer towards same memory, to be able to set off any change detections. If that's not it, please show some more code logic.