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

如何让Angular中*ngIf指令元素仅在API响应后显示

解决验证API响应前显示状态按钮的问题

问题核心是当前element.HAS_ERROR默认值为false或undefined,导致页面加载后直接显示绿色done按钮。我们需要给每个元素增加一个“验证是否完成”的标记,只有API响应后才显示对应状态按钮。

步骤1:给元素添加初始状态标记

在数据初始化/加载逻辑中,给每个待验证的element添加isValidationCompleted字段,初始设为false:

// 假设你的数据数组是this.reservationList
this.reservationList.forEach(item => {
  item.isValidationCompleted = false;
  item.HAS_ERROR = false; // 可选,明确初始无错误状态
});

步骤2:修改API请求函数,更新验证完成状态

完善asyncReq函数,在API成功和失败的回调中,都将element.isValidationCompleted设为true,同时处理Promise的resolve和reject:

asyncReq(element:any){
  this.conflictData = null;
  let startDate:any;
  let endDate:any;
  startDate = this.easternToUtc.transform(moment(element.START_TIME).format('YYYY/MM/DD 00:00:00'), this.selectedTimeZone);
  endDate =  this.easternToUtc.transform(moment(element.END_TIME).format('YYYY/MM/DD 23:59:59'), this.selectedTimeZone);
  
  return new Promise((resolve, reject) => {
    let requestPayload = zipObj(
      ['USER_ID','AMENITY_TYPE_ID','AMENITY_ID','START_TIME', 'END_TIME', 'BUILDING_ID', 'AMENITY_NAME'],
      [element.USER_ID,element.AMENITY_TYPE_ID,element.AMENITY_ID,startDate, endDate, element.BUILDING_ID, element.AMENITY_NAME]
    );
    
    this.http.post(`${environment.reservationValidation}`, requestPayload).pipe(take(1)).subscribe(
      (successResponse) => {
        // 验证通过:标记无错误+验证完成
        element.HAS_ERROR = false;
        element.isValidationCompleted = true;
        resolve(successResponse);
      }, 
      (error:any) => {
        console.log(error);
        element.ERROR_TYPE = error.error?.message;
        element.HAS_ERROR = true;
        element.isValidationCompleted = true;
        this.conflictData = error.error?.reservationdata;
        reject(error);
      }
    );
  });
}

步骤3:修改HTML模板,限制按钮显示条件

只有当isValidationCompleted为true时,才根据HAS_ERROR的值显示对应的按钮:

</mat-header-cell>
<mat-cell style="max-width: 6%;" *matCellDef="let element; let i=index">
  <!-- 验证完成且无错误时显示done按钮 -->
  <button *ngIf="element.isValidationCompleted && !element.HAS_ERROR" mat-icon-button>
    <span class="material-icons" style="color: #55bd55;">done</span>
  </button>

  <!-- 验证完成且有错误时显示错误按钮 -->
  <button mat-icon-button color="warn" *ngIf="element.isValidationCompleted && element.HAS_ERROR" (click)="openConflictDialog(i)">
    <span class="material-icons">
      info
    </span>
  </button>
</mat-cell>
</ng-container>

这样修改后,在API返回响应之前,两个按钮都不会显示,只有验证完成后才会根据结果展示对应的状态按钮。

内容的提问来源于stack exchange,提问作者Neeti Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:05:22