Сообщение Snackbar не меняется в реальном времени - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь изменить некоторые данные в сообщении закусочной, но сообщение не меняется.

Вот небольшой пример того, что я пытаюсь сделать:

https://stackblitz.com/edit/angular-snackbar-qvxipb?file=app%2Fapp.component.html

Desirable Behavior: 
Redirecting in 3s -> Redirecting in 2s -> Redirecting in 1s 

Кто-нибудь может мне помочь? Спасибо.

Редактировать: без необходимости открывать несколько закусочных.

1 Ответ

0 голосов
/ 17 октября 2019

Я знаю, что может быть проблема с 'MatSnackBar'. Они появятся и исчезнут, не зная, существует ли конфигурация, чтобы предотвратить это, поэтому я отправляю ответ с решением, используя директиву.

component.ts

export class SnackTimerComponent {

  timer: number = 5
  message: string

  startCountdown() {
    this.timer = 5
    let interval = setInterval(() => {
      if (this.timer != 0) {
        this.timer--
        console.log(this.timer);
        this.message = `Redirecting in ${this.timer}s...`;
      } else {
        clearInterval(interval)
        this.message = null
      }
    }, 1000);
  }

}

directive.ts

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[snack-bar-timer]'
})
export class SnackBarTimerDirective {

  @Input() color: string = "#b5e7a0"

  constructor(el: ElementRef) {
    const style = el.nativeElement.style
    style.backgroundColor = this.color
    style.position = "absolute"
    style.left = "50%"
    style.bottom = "0"
    style.transform = "translateX(-50%)"
    style.padding = "20px"
    style.margin = "12px"
    style.width = "fit-content"
    style.borderRadius = "8px"
  }

}

component.html

<button (click)="startCountdown()">Start countdown</button>
<div *ngIf="message" snack-bar-timer>{{message}}</div>
...