Switch themes in angular material 5

前端 未结 4 1379
一整个雨季
一整个雨季 2020-12-08 11:06

I been reading a few articles on this but they seem to be conflicting in several different ways. I am hoping to re-create the same theme switching as the angular material do

4条回答
  •  无人及你
    2020-12-08 11:43

    You have to use the getContainerElement method of OverlayContainer. Here's some example usage:

    this.overlay.getContainerElement().classList.add('my-theme');
    

    As for your style files, I strongly suggest removing this line for both custom-theme.scss and light-custom-theme.scss (you only need it for your classes in this case):

    @include angular-material-theme($custom-theme); // Remove this line from custom-theme.scss and light-custom-theme.scss
    

    If you also want to toggle the theme for your app, you should probably use this in the same toggleTheme method:

    toggleTheme(): void {
      if (this.overlay.classList.contains("custom-theme")) {
        this.overlay.classList.remove("custom-theme");
        this.overlay.classList.add("light-custom-theme");
      } else if (this.overlay.classList.contains("light-custom-theme")) {
        this.overlay.getContainerElement().classList.remove("light-custom-theme");
        this.overlay.classList.add("custom-theme");
      } else {
        this.overlay.classList.add("light-custom-theme");
      }
      if (document.body.classList.contains("custom-theme")) {
        document.body.classList.remove("custom-theme");
        document.body.classList.add("light-custom-theme");
      } else if (document.body.classList.contains("light-custom-theme")) {
        document.body.classList.remove("light-custom-theme");
        document.body.classList.add("custom-theme");
      } else {
        this.overlay.classList.add("light-custom-theme");
      }
    }
    
    • More info on theming
    • Stackblitz demo (For the demo, I had to nest the app in a Sidenav)

提交回复
热议问题