【问题标题】:Snackbar message doesn't change in real timeSnackbar 消息不会实时更改
【发布时间】:2020-02-13 20:15:00
【问题描述】:

我正在尝试更改快餐栏消息中的一些数据,但消息没有改变。

这是我正在尝试做的一个小例子:

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

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

有人可以帮助我吗?谢谢。

编辑:无需打开多个小吃店。

【问题讨论】:

  • 第一种方式只是将this.snackBar代码移动到setInterval()函数的末尾。
  • 这会打开多个snackbars,我想在同一个snackbar 上更改它=/
  • 是的,我知道。使用指令或组件制作自己的零食。小吃店一一显示不知道是否有任何选项可以防止这样做。
  • 嗯好的,谢谢你的回答。我会尝试这种方法。

标签: javascript angular angular-material


【解决方案1】:

我知道“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>

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2014-01-15
    • 2020-08-06
    • 2021-03-03
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    相关资源
    最近更新 更多