Angular Event Emitting для изменения темы материала - PullRequest
0 голосов
/ 29 апреля 2020

Пожалуйста, я хочу изменить тему моего приложения, выбрав один из цветов, отображающих изображение. У меня есть следующие компоненты:

  • Компонент заголовка (путь: 'src / app / shared / components / header')
  • Компонент по умолчанию (путь: 'src / app / layouts / default ')

    Изображение ниже является компонентом по умолчанию, содержащим компонент заголовка.

Image showing theme colors to be selected for my angular app

заголовок. компонент. html

    <mat-toolbar color="primary">
  <mat-toolbar-row>
    <button mat-icon-button (click)="toggleSideBar()">
      <mat-icon>menu</mat-icon>
    </button>

    <span>APP LOGO</span>

    <div fxFlex fxLayout="row" fxLayoutAlign="flex-end">
      <ul fxLayout="row" fxLayoutGap="20px">
        <li>
          <button mat-icon-button [matMenuTriggerFor]="theme">
            <mat-icon>format_color_fill</mat-icon>
          </button>
          <mat-menu #theme="matMenu">
            <div class="btn-wrapper">
              <button mat-mini-fab class="btn btn-default" (click)="selectedTheme='default'"></button>
              <button mat-mini-fab class="btn btn-purple" (click)="selectedTheme='purple'"></button>
              <button mat-mini-fab class="btn btn-pink" (click)="selectedTheme='pink'"></button>
              <button mat-mini-fab class="btn btn-deep-orange" (click)="selectedTheme='deep-orange'"></button>
            </div>
          </mat-menu>
        </li>
        <li>
          <button mat-icon-button>
            <mat-icon>settings</mat-icon>
          </button>
        </li>
        <li>
          <button mat-button [matMenuTriggerFor]="menu">
            <mat-icon>person_outline</mat-icon>
          </button>
          <mat-menu #menu="matMenu">
            <button mat-menu-item>
              <mat-icon>exit_to_app</mat-icon>
              Sign out
            </button>
          </mat-menu>
        </li>
      </ul>
    </div>
  </mat-toolbar-row>
</mat-toolbar>

header.component.ts

    import {Component, EventEmitter, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  @Output() toggleSideBarForMe: EventEmitter<any> = new EventEmitter();
  @Output() selectedTheme: string;

  constructor() { }

  ngOnInit(): void {
  }

  toggleSideBar(){
    this.toggleSideBarForMe.emit();
    setTimeout(() => {
      window.dispatchEvent(
        new Event('resize')
      );
    }, 300);
  }

}

default.component. html

    <div [ngClass]="selectedTheme">
  <app-header (toggleSideBarForMe)="toggle()"></app-header>

  <mat-drawer-container>
    <mat-drawer mode="side" [opened]="sideBarOpen">
      <app-sidebar></app-sidebar>
    </mat-drawer>
    <mat-drawer-content>
      <router-outlet></router-outlet>
    </mat-drawer-content>
  </mat-drawer-container>
  <app-footer></app-footer>
</div>

default.component.ts

 import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-default',
  templateUrl: './default.component.html',
  styleUrls: ['./default.component.scss']
})
export class DefaultComponent implements OnInit {

  sideBarOpen = true;

  constructor() {
  }

  ngOnInit(): void {
  }

  toggle(){
    this.sideBarOpen = !this.sideBarOpen;
  }
}

Вот мой файл пользовательской темы: custom-theme.s css

    @import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$my-app-primary: mat-palette($mat-indigo);
$my-app-accent:  mat-palette($mat-pink);

// The warn palette is optional (defaults to red).
$my-app-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$my-app-theme: mat-light-theme($my-app-primary, $my-app-accent, $my-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($my-app-theme);

.alternate-teal-theme {
  $teal-app-primary: mat-palette($mat-teal);
  $teal-app-accent:  mat-palette($mat-yellow);

  // The warn palette is optional (defaults to red).
  $teal-app-warn:    mat-palette($mat-red);

  // Create the theme object (a Sass map containing all of the palettes).
  $teal-app-theme: mat-light-theme($teal-app-primary, $teal-app-accent, $teal-app-warn);

  // Include theme styles for core and each component used in your app.
  // Alternatively, you can import and @include the theme mixins for each component
  // that you are using.
  @include angular-material-theme($teal-app-theme);
}

.purple {
  $purple-primary: mat-palette($mat-purple);
  $purple-accent: mat-palette($mat-light-green);
  $purple-theme: mat-light-theme($purple-primary, $purple-accent);
  @include angular-material-theme($purple-theme);
}
.pink {
  $pink-primary: mat-palette($mat-pink);
  $pink-accent: mat-palette($mat-yellow);
  $pink-theme: mat-light-theme($pink-primary, $pink-accent);
  @include angular-material-theme($pink-theme);
}

.deep-orange {
  $deep-orange-primary: mat-palette($mat-deep-orange);
  $deep-orange-accent: mat-palette($mat-teal, A100);
  $deep-orange-theme: mat-light-theme($deep-orange-primary, $deep-orange-accent);
  @include angular-material-theme($deep-orange-theme);
}

Пожалуйста, как сделать так, чтобы выбранная тема вступила в силу в приложении?

1 Ответ

1 голос
/ 30 апреля 2020

Содержимое файла custom-theme.scss должно быть передано или импортировано в ваш style.scss. Чтобы тема влияла на все приложение, вы должны объявить класс css того же класса в div, который включает в себя html содержимое вашего компонента boostrap. И ошибка, которую я замечаю в вашем коде, состоит в том, что в файле header.component.ts выходные данные выбранной темы не генерируют никаких событий, вы должны объявить это следующим образом @Output() selectedTheme: EventEmitter<string> = new EventEmitter<string>();, здесь я оставляю вам рабочий пример всего, что я только что объяснил : stackblitz

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...