Adjust style sizes according to different languages

The app I’m working on supports two languages, but one language (German) usually takes up a lot of space. How can I adjust the components/CSS sizes when the user switch the languages?

I have a popover which the width fit for German but it’s too large for English language, so I wanna know if there is some other alternative besides the hardcoded size in the stylesheet. Thank you

The answer to this probably depends heavily on what mechanism you’re using to manage i18n.

Hi rapropos, I’m using:

@ngx-translate/core

In that case, you have an onLangChange hook, off which you can hang one of the extremely rare times I’m going to recommend more-or-less direct DOM mogrification.

This code is totally untested because I don’t have any ngx-translate scratchpad apps lying around, but hopefully will give you enough of a push start to get you going:

interface CssProperty {
  propname: string;
  value: string;
}
@Injectable()
class StyleMonster {
  cssPropMap: { [lang: string]: CssProperty[] } = {
    "de": [ {propname: "--popover-width", value: "18rem"} ],
    "en": [ {propname: "--popover-width", value: "12rem"} ],
  };
  constructor(
    private domcon: DomController, 
    @Inject(DOCUMENT) private document: Document,
    private xlator: TranslateService) {
      xlator.onLangChange.subscribe(evt => {
        let cssProps = this.cssPropMap[evt.lang] || [];
        this.domcon.write(() => {
          let styledec = this.document.documentElement.style;
          cssProps.forEach(cssProp => {
            styledec.setProperty(cssProp.propname, cssProp.value);
          });
        });
      });
    }
}

This effectively alters any global CSS variables when the language changes. I’ve used a variant of this technique to inject custom colors into Ionic apps at runtime, and I think it could do your job here.

Thanks a lot, working!