0

I'm creating a directive that formats a date based on the user's timezone. The user has the option to update their timezone via a settings dropdown on the page. Therefore, the directive is subscribing to timezone updates and updating on change.

ngOnInit() {
    this.timezoneUpdatedSubscription = this.commonService.timezoneUpdated.subscribe(() => {
        this.el.nativeElement.innerHTML = moment(this.localDate).tz(this.commonService.usersTimezone).format(this.format);
    })
}

ngOnDestroy() {
    if (this.timezoneUpdatedSubscription) {
        this.timezoneUpdatedSubscription.unsubscribe();
    }
}

The possible issue is that this directive might be used a large number of times on a page, likely 50 times but possibly 200+ times at times. This means there could be 200+ subscriptions at a time.

Would this cause a performance issue with a large number of elements being updated at once? I couldn't see any documentation to suggest either way.

DJDMorrison
  • 1,302
  • 2
  • 17
  • 34
  • if you mean what is the best practice to subscribe/unsubscribe, the code looks good. if the parent component is the same for all elements with this directive then you can subscribe once in component level then transform your solution to `pipe` and then pass timezone to `pipe`. – Mazdak Sep 07 '21 at 13:51
  • Sorry clarified the question - I meant more in terms of performance of updating a large number of elements at once – DJDMorrison Sep 07 '21 at 14:09
  • When it comes to the performance, you should disable angular change detection which runs by default. It can save you a lot of performance related tuning. It would be easy if you are using any state management lib. – Apoorva Chikara Sep 08 '21 at 16:14

1 Answers1

0

It depends how are you using it. Normally, ngOnDestroy hook helps to remove such subscription provided that component is being destroyed. If you pushing every time new component and not removing it, yes, it will create a memory leak. It will only we unsubscribe if we destroy the component and re-render it in which case it won't cause any memory leaks.

I'm not sure how are you using it with the given code, but I would suggest you to use pipe to change the format on view. If you wanted to keep this formatted date for future use it is fine to use subs/pub pattern.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Thanks Apoorva. Definitely destroying the component and unsubscribing so I think it'd avoid memory leaks. Also, the reason for not using pipe is that it wouldn't update when the timezone changes as pipes only update when the input changes, not the 'modifier'. – DJDMorrison Sep 07 '21 at 13:44
  • Yes, pipe could be little bit tricky. But when you update any property on view angular runs the changes detection by default or you can run it which might help you to use pipe. Anyways does the answer helps you? or you were looking something specific? – Apoorva Chikara Sep 07 '21 at 15:22