programing

Angular material $ mdToast의 메시지 유형에 따라 Toast의 색상을 어떻게 변경할 수 있습니까?

kingscode 2021. 1. 17. 10:57
반응형

Angular material $ mdToast의 메시지 유형에 따라 Toast의 색상을 어떻게 변경할 수 있습니까?


사용 $mdToast.simple().content("some test")하는 동안 토스트가 검은 색으로 보입니다. 해당 색상을 빨간색, 노란색 등으로 변경하려면 오류, 경고 및 성공과 같은 오류 메시지 유형에 따라 다릅니다.

유사한 질문 .


편집 :
올바른 구현을 위해 아래 rlay3s 솔루션을 사용하십시오 :)!

구식 :
jhblacklocks 솔루션으로 사용자 지정 텍스트를 표시하는 데 문제가 있었기 때문에 '템플릿'을 사용하여 이렇게하기로 결정했습니다.

var displayToast = function(type, msg) {

    $mdToast.show({
        template: '<md-toast class="md-toast ' + type +'">' + msg + '</md-toast>',
        hideDelay: 6000,
        position: 'bottom right'
    });
};

또한 .css 파일에 다른 유형을 추가했습니다.

.md-toast.error {
    background-color: red;
}

.md-toast.success {
    background-color: green;
}

이것이 가장 아름다운 접근 방식인지 모르겠지만 각 대화 상자 유형에 대한 템플릿 파일이 필요하지 않으며 사용자 지정 텍스트를 표시하는 것은 정말 쉽습니다.


테마를 지정하는 더 쉬운 방법이 있습니다.

$mdToast.simple().content("some test").theme("success-toast")

그리고 CSS에서 :

md-toast.md-success-toast-theme {
    background-color: green;
    ...
}

메시지 유형을 통합하여 테마를 동적으로 선택할 수 있습니다.

업데이트 : Charlie Ng가 지적했듯이 등록되지 않은 사용자 정의 테마 사용과 관련된 경고를 피하기 위해 테마 공급자를 사용하여 모듈에 등록하십시오.$mdThemingProvider.theme("success-toast")

또 다른 업데이트 : 2015 년 12 월 2 일 (v1.0.0 +)에 생성 된 주요 변경 사항 이 있습니다 . 이제 다음을 지정해야합니다.

md-toast.md-success-toast-theme {
    .md-toast-content {
        background-color: green;
        ...
    }
}

테마 등록 :

$mdThemingProvider.theme("success-toast");
$mdThemingProvider.theme("error-toast");

CSS 추가 :

md-toast.md-error-toast-theme div.md-toast-content{
    color: white !important;
    background-color: red !important;
}

md-toast.md-success-toast-theme div.md-toast-content{
    color: white !important;
    background-color: green !important;
}

사용하다:

$mdToast.show(
    $mdToast.simple()
        .content(message)
        .hideDelay(2000)
        .position('bottom right')
        .theme(type + "-toast")
);

이 링크에서 요소의 배경색을 변경할 수 없음을 알 수 있으며 항상 고정됩니다.

https://github.com/angular/material/blob/master/src/components/toast/toast-theme.scss

토스트에 대한 머티리얼 디자인 지침에 배경이 항상 동일하게 유지된다고 명시되어 있기 때문입니다.

https://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs

사양 목록 background항목을 확인합니다 .

각 상황에서 텍스트 색상에 대해 언급 된 것은 없으며 backgroundPalette, GitHub 링크의 해당 CSS에 선언 된 '50'색조 회전 에서 ,를 따른다는 것을 의미합니다 .

warn토스트 또는 accent-ted 토스트를 기본값과 구별하는 방법으로 action toast, 각각 적절한 클래스 ( md-warn또는 md-accent)를 사용하는 작업 버튼 있는를 호출합니다 .

$mdToast.show({
    template: '<md-toast>\
        {{ toast.content }}\
        <md-button ng-click="toast.resolve()" class="md-warn">\
            Ok\
        </md-button>\
    </md-toast>',
    controller: [function () {
        this.content = 'Toast Content';
    }],
    controllerAs: 'toast'
});

default형태는 성공을 암시하는 행동 보고서를 의미하는 토스트 자체 입니다. 더 많은주의가 필요한 경우 '재시도', '문제 신고', '세부 정보'와 같은 작업을 추가 하는 작업 버튼을 설정하여 강제로 닫으세요. 이 클릭을 포착하고 일부 기술 정보를 기록하는 데 사용할 수 있습니다. .. 예제는 필요한 것과 다릅니다.


rlay3의 답변에 한 단계 더 있습니다.

0.7.1의 Angular Material은 등록되지 않은 테마에 경고를 추가했습니다. https://github.com/angular/material/blob/master/CHANGELOG.md#071--2015-01-30

테마가 등록되지 않은 경우 알림이 표시 될 때마다 다음과 같은 경고 메시지가 콘솔에 표시됩니다.

attempted to use unregistered theme 'custom-toast'
angular.js:12416 Attempted to use unregistered theme 'custom-toast'. 
Register it with $mdThemingProvider.theme().

경고를 없애려면 Angular 앱에서 'custom-toast'테마를 구성해야합니다.

angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {
  $mdThemingProvider.theme('custom-toast')
});

다음과 같이 사용하십시오.

$mdToast.simple().content("some test").theme("custom-toast");

참조 : https://material.angularjs.org/latest/#/Theming/04_multiple_themes


간단한 건배 전화 사용에 대해 물어 보셨습니다. 데모같은 사용자 지정 토스트 쇼를 시도 하고 템플릿에 클래스를 추가 하시겠습니까?

JS

$mdToast.show(
  controller: 'ToastCtrl',
  templateUrl: 'views/shared/toast.html',
  hideDelay: 6000,
  position: $scope.getToastPosition()
)

주형

<md-toast class="flash">
  <span flex>Custom toast!</span>
  <md-button ng-click="closeToast()">
   Close
  </md-button>
</md-toast>

CSS

md-toast.flash {
  background-color: red;
  color: white;
}

컨트롤러 (커피)

'use strict'

###*
 # @ngdoc function
 # @name angularApp.controller:ToastCtrl
 # @description
 # # ToastCtrl
 # Controller of the angularApp
###
angular.module('angularApp')
  .controller 'ToastCtrl', ($scope) ->
    $scope.closeToast = ()->
      $mdToast.hide()

다른 옵션을 제공하기 위해 이러한 방식으로 쉽게 인스턴스화 할 수있는 $mdToast토스트 사전 설정 을 정의 할 수 있습니다. 텍스트 내용을 변경하는 방법을 이해하는 데 어려움을 겪고 있습니다.

$mdToast.show(
  $mdToast.error()
);

사전 설정 에 설명 된 바와 같이 정의된다 https://material.angularjs.org/latest/api/service/ $ mdToast :

$mdToastProvider.addPreset('error', {
  options: function() {
    return {
      template:
        '<md-toast>' +
          '<div class="md-toast-content">' +
          '</div>' +
        '</md-toast>',
      position: 'top left',
      hideDelay: 2000,
      toastClass: 'toast-error',
      controllerAs: 'toast',
      bindToController: true
    };
  }
});

처음에는 솔루션을 선호했지만 건배를 위해 테마 공급자에서 테마를 설정하는 것을 좋아하지 않습니다. 이 솔루션은 어떻습니까?

JS (커피)

   if error
      message = ''

      if error.reason is 'Incorrect password'
        message = 'Email and password combination is incorrect'
      if error.reason is 'User not found'
        message = 'No account found with this email address'

      $mdToast.show(
        templateUrl:  'client/modules/toasts/toastError.html'
        hideDelay:    3000
        controller: ( $scope ) ->
          $scope.message    =  message
          $scope.class      = 'error'
          $scope.buttonLabel = 'close'
          $scope.closeToast = ->
            $mdToast.hide()
      ).then( ( result ) ->
        if result is 'ok'
          console.log('do action')
      )

그런 다음 HTML (JADE)

md-toast(ng-class="class")
  span(flex) {{message}}
  md-button.md-action(ng-click="closeToast()") {{buttonLabel}}

I tried to use the locals option to pass variables to the controller, but for some reason they are not injected.(https://material.angularjs.org/latest/#/api/material.components.toast/service/$mdToast check list of options under show function)

Then last the CSS (STYLUS)

md-toast.success
  background-color    green

md-toast.error
  background-color    red

Summary: there is on template in this case which you can give custom placeholders which you prefill in your controller. This solution works for me.


You can do it with factory and some css.

(function () {
  'use strict';

  angular
    .module('app.core')
    .factory('ToastService', ToastService);

  /** @ngInject */
  function ToastService($mdToast) {

    var service = {
      error: error,
      success: success,
      info : info
    };

    return service;

    //////////

    function success(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-success")
          .textContent(text)
      );
    }

    function info(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-info")
          .textContent(text)
      );
    }

    function error(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-error")
          .textContent(text)
      );
    }
  }
}());

And css.

.toast-error .md-toast-content{
  background-color: rgb(102,187,106) !important;
}

.toast-info .md-toast-content{
  background-color: rgb(41,182,246) !important;
}

.toast-error .md-toast-content{
  background-color: rgb(239,83,80) !important;
}

ReferenceURL : https://stackoverflow.com/questions/28481029/how-can-i-change-the-color-of-toast-depends-on-message-type-in-angular-material

반응형