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.
It depends how are you using it. Normally,
ngOnDestroyhook 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
pipeto change the format on view. If you wanted to keep this formatted date for future use it is fine to use subs/pub pattern.