請問語系變更動態載入css檔案

我想根據語系切換,能夠動態載入assets/css下的css檔案
目前做法如下
component.ts


app.module.ts

index.html
image
透過ng serve測試時,在F12 network的頁籤會看到網站一直不斷訪問同一個css檔案

請問這樣有甚麼辦法解決嗎?

加上 changeDetection: ChangeDetectionStrategy.OnPush, 並手動控制 ChangeDetectionRef ,決定更新時間點

import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { LanguageService } from '../language.service';

@Component({
  selector: 'app-css-loader',
  template: `
    <link rel="stylesheet" type="text/css" [href]="cssPath" />
  `,
  styleUrls: ['./css-loader.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CssLoaderComponent implements OnInit {
  path;

  constructor(
    private sanitizer: DomSanitizer,
    private service: LanguageService,
    private cd: ChangeDetectorRef
  ) {
    this.service.lang$.subscribe(val => {
      this.cssPath = `/assets/css/${val}.css`;
      this.cd.markForCheck();
    });
  }

  ngOnInit() {}

  set cssPath(path) {
    this.path = path;
  }

  get cssPath() {
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.path);
  }
}
1個讚