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

如何动态调整mat-toolbar的标题位置从居中切换为左对齐?

实现方案

利用Angular的条件类绑定结合Flex布局即可实现,判断逻辑和按钮的显示逻辑复用currentUser变量即可,不需要额外新增状态。

完整代码修改

1. 模板(HTML)修改

<mat-toolbar color="primary" [ngClass]="{'has-buttons': currentUser}">
  <h1 id="app-title">{{title}}</h1>
  <div class="buttons" *ngIf="currentUser">
    <button mat-button routerLink="/" routerLinkActive="active">Home</button>
    <button mat-button>About</button>
    <button mat-button>Contact</button>
    <button mat-button>Profile</button>
    <button mat-button (click)="logout()">Logout</button>
  </div>
</mat-toolbar>

修改说明:给mat-toolbar加了条件类has-buttons,当currentUser存在时自动生效,同时移除了无用的双向绑定[(ngClass)]。

2. 样式(CSS/SCSS)修改

mat-toolbar {
  display: flex;
  align-items: center;
}

#app-title {
  /* 默认无按钮时居中 */
  margin: 0 auto;
}

/* 有按钮时标题左对齐 */
mat-toolbar.has-buttons #app-title {
  margin-left: 0;
  margin-right: 16px; /* 可根据需要调整标题和按钮之间的间距 */
}

.buttons {
  display: flex;
  gap: 8px; /* 调整按钮之间的间距 */
  /* 如果需要按钮靠右排列,新增下面一行样式即可 */
  /* margin-left: auto; */
}

逻辑说明:

  • 默认状态下没有按钮,#app-title的左右margin为auto,会在flex容器中自动居中,符合无元素时的居中要求
  • 存在按钮时,has-buttons类生效,重置标题的左margin为0,标题自动靠左对齐,按钮区域可以正常排列在标题右侧

效果演示

  • 左对齐效果(存在按钮时):
    左对齐
  • 居中效果(无按钮时):
    居中

内容的提问来源于stack exchange,提问作者just askin'

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 17:36:03