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

Angular中如何根据条件渲染按钮并调用对应函数?

解决方案

方法1:通过*ngIf条件渲染对应按钮

根据modaldata.id的存在与否,分别渲染编辑或新建状态的按钮:

<button 
  type="button" 
  class="btn btn-primary ms-4" 
  (click)="update()"
  *ngIf="modaldata.id"
>
  Save
</button>

<button 
  type="button" 
  class="btn btn-primary ms-4" 
  (click)="create()"
  *ngIf="!modaldata.id"
>
  Add
</button>

方法2:动态绑定按钮文本与点击事件

只使用一个按钮,通过三元表达式动态设置显示文本和触发的函数:

<button 
  type="button" 
  class="btn btn-primary ms-4"
  (click)="modaldata.id ? update() : create()"
>
  {{ modaldata.id ? 'Save' : 'Add' }}
</button>

两种方法都能满足需求:

  • 当modaldata.id存在时,按钮显示「Save」,点击调用update()
  • 当modaldata.id不存在时,按钮显示「Add」,点击调用create()

内容的提问来源于stack exchange,提问作者Mohammad Rehan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:01:17