I am working with multilingual project with angular and the logic for changing the language and the stylesheets is typed in the app default component, I created navbar component but I can't use the changeLanguage function because it's in the app component so I must duplicate the function and the logic in every component I make, how to solve this or how to make the functions in the app component useable in the other components?
the app components code
import { Component } from '@angular/core';
import { TranslateService } from "@ngx-translate/core";
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'labsystem';
constructor(private translateService: TranslateService, @Inject(DOCUMENT) private document:
Document) { }
changeLanguage(lang: string) {
let htmlTag = this.document.getElementsByTagName('html')[0] as HTMLHtmlElement;
htmlTag.dir = lang === "ar" ? "rtl" : "ltr";
this.translateService.setDefaultLang(lang);
this.translateService.use(lang);
this.changeCssFile(lang);
}
changeCssFile(lang: string) {
let headTag = this.document.getElementsByTagName("head")[0] as HTMLHeadElement;
let existingLink = this.document.getElementById("langCss") as HTMLLinkElement;
let bundleName = lang === "ar" ? "arabicStyle.scss" : "englishStyle.scss";
if (existingLink) {
existingLink.href = bundleName;
} else {
let newLink = this.document.createElement('link');
newLink.rel = "stylesheet";
newLink.id = "langCss";
newLink.href = bundleName;
headTag.appendChild(newLink);
}
}
}
I need to use these functions in the other components
CodePudding user response:
you can create a constant file like app.constant.ts and there you can do
export myFunction = () => {
// your code here
}
and, simply call that function by reference everywhere.
import {myFunction} from './app.constant'