You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据布尔值更改Angular Snackbar的显示内容?

解决方案

Angular Material的自定义Snackbar组件可通过data配置项接收外部传递的数据,具体实现步骤如下:


1. 在App组件中传递布尔值到Snackbar

修改app.component.ts的openSnackBar方法,添加参数接收注册状态,并通过data字段传递给Snackbar组件:

openSnackBar(isRegistrationSuccessful: boolean){
  this.snackbar.openFromComponent(SnackbarComponent, {
    duration: 2000,
    data: { isRegistrationSuccessful: isRegistrationSuccessful } // 传递注册状态
  });
}

在模板中调用方法时,根据实际注册结果传入对应布尔值(示例直接传true,实际项目替换为注册逻辑的返回值):

<button mat-raised-button type="submit" id="registerButton" (click)="openSnackBar(true)">
  <p id="registerText">Register</p>
</button>

2. 在Snackbar组件中接收并使用传递的数据

修改snackbar.component.ts,注入MAT_SNACK_BAR_DATA获取传递的数据,并赋值给组件内变量:

import { Component, OnInit, inject } from '@angular/core';
import { MatSnackBarRef, MAT_SNACK_BAR_DATA } from '@angular/material/snack-bar';

export class SnackbarComponent implements OnInit {
  isRegistrationSuccessful: boolean = false;
  
  snackBarRef = inject(MatSnackBarRef);
  // 注入外部传递的数据
  private snackBarData = inject(MAT_SNACK_BAR_DATA);

  constructor() { }

  ngOnInit() {
    // 将传递的注册状态赋值给组件变量
    this.isRegistrationSuccessful = this.snackBarData.isRegistrationSuccessful;
  }
}

3. 优化模板判断逻辑(可选)

将模板中的判断简化为更简洁的写法(原逻辑也可正常运行):

<span class="text" matSnackBarLabel *ngIf="isRegistrationSuccessful; else registrationFailed">
  You have registered successfully
</span>
<span matSnackBarActions>
  <button mat-button matSnackBarAction (click)="snackBarRef.dismissWithAction()">🍕</button>
</span>

<ng-template #registrationFailed>
  <span class="text" matSnackBarLabel>
    Failed to register
  </span>
  <span matSnackBarActions>
    <button mat-button matSnackBarAction (click)="snackBarRef.dismissWithAction()">🍕</button>
  </span>
</ng-template>

内容的提问来源于stack exchange,提问作者Tony Ortega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:35:16