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

Angular函数返回多值如何直接在HTML模板使用无需TS变量存储

解决方案
  • 方案1:使用*ngIf别名语法缓存返回值(无需修改TS逻辑)
    该方案只需调整HTML结构,即可实现单次调用函数、多次使用返回值的需求,不会生成多余DOM节点,也不需要拆分函数或提前在TS中声明变量存储结果。
    修改后的HTML代码如下:
<!-- 缓存getClass返回值为临时变量classInfo,函数仅执行一次 -->
<ng-container *ngIf="getClass('investing', 'plan') as classInfo">
  <div *ngIf="classInfo[0]"
       class="prio_box dnd_move"
       data-drag="list-1"
       data-drag-index="0">

    <span [ngClass]="classInfo[1]" 
        class="dnd_move clr-box">
    </span>

    <span class="drag_content dnd_move">Plan</span>

  </div>
</ng-container>
  • 方案2:优化返回值结构提升可维护性(可选)
    如果不想记忆数组索引对应的返回值含义,可以将函数返回值从数组调整为语义化对象,后续迭代不会出现索引对应错误的问题。
    修改后的TS代码如下:
getClass(component: string, value: any) {
    component = component.toLowerCase();
    value = value.replace(/\s/g, "");
    let pathValue = this.control[component]
      ? this.control[component.toLowerCase()][value]
      : null;
    this.allGreen.add(pathValue);
    const className = pathValue == Status.Yes
      ? "green_box"
      : pathValue == Status.DontKnow
      ? "yellow_box"
      : "red_box";
    const showEl = pathValue == Status.Yes
      ? false
      : pathValue == Status.DontKnow
      ? true
      : true;
    return { showEl, className };
}

对应的HTML调用代码:

<ng-container *ngIf="getClass('investing', 'plan') as classInfo">
  <div *ngIf="classInfo.showEl"
       class="prio_box dnd_move"
       data-drag="list-1"
       data-drag-index="0">

    <span [ngClass]="classInfo.className" 
        class="dnd_move clr-box">
    </span>

    <span class="drag_content dnd_move">Plan</span>

  </div>
</ng-container>

内容的提问来源于stack exchange,提问作者Kuldeep Singh Chouhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:15:03