【问题标题】:Avoid functions in template in case of ul list在 ul 列表的情况下避免模板中的函数
【发布时间】:2022-12-05 19:36:04
【问题描述】:

在这种情况下(简化)如何避免在模板中使用函数?

post.component.ts

import { Details, Status } from 'models';

export class PostComponent implements OnInit {
  @Input() pckgs: Details[];
  //...

  myFunc2(pckg: Details) {
    return pckg.status === Status.P ? 'processing' : pckg.status === Status.D ? 'finished' : '';
  }  
}

post.component.html

<ul>
  <li *ngFor="let pckg of pckgs; trackBy: trackId">
    <span [ngClass]="myFunc1(pckg)">{{myFunc2(pckg)}}</span>
  </li>
</ul>

我相信它可以类似于 method called in ngFor gets trigger for multiple times 某种程度上,但在那个例子中它不是 ngFor="let item of项目”。

【问题讨论】:

    标签: angular typescript function templates


    【解决方案1】:

    使用纯管道。

    HTML

    <ul>
      <li *ngFor="let pckg of pckgs; trackBy: trackId">
        <span [ngClass]="myFunc1(pckg)">{{ pckg | statusDisplay }}</span>
      </li>
    </ul>
    

    管道

    @Pipe({ name: 'statusDisplay', pure: true })
    export class StatusDisplayPipe implements PipeTransform {
      transform(pckg: Details): string {
        return pckg.status === Status.P ? 'processing' : pckg.status === Status.D ? 'finished' : '';
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多