I'm using angular 6 and ngx-translate. This is my switch language function
switchLanguage(language: string) {
this.translate.use(language);
if (language !== 'ar' && document.getElementsByTagName('html')[0].hasAttribute('dir')) {
document.getElementsByTagName('html')[0].removeAttribute('dir');
} else if (language === 'ar' && !document.getElementsByTagName('html')[0].hasAttribute('dir')) {
document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl');
}
// if this line worth it?
if (language !== JSON.parse(localStorage.getItem('lang'))) {
localStorage.setItem('lang', JSON.stringify(language));
}
}
I'm asking about this line in particular
if (language !== JSON.parse(localStorage.getItem('lang')))
If I don't use it, it means that if the language is english and you switch it to english, the localStorage is going to be updated. If I use it however, it means that, every time you switch a language, it's going to read localstorage to check its value before updating.
Is the cost of just setting the language better than the cost of checking it first?
This method is getting called whenever you switch the language and in app.ts
constructor, so basically on every page load. Is there a better way to do it?
document.getElementById
tends to imply that HTML is being used. \$\endgroup\$