在Angular的*ngIf表达式中,这么多冒号是做什么用的?

huangapple go评论54阅读模式
英文:

What do so many colons do in Angular *ngIf expression?

问题

例如:

*ngIf="step?.salaryChangedBy?.updated | issalaryUpdated : lastViewedByUser : step?.salaryChangedBy?.userId : userId"

或者格式化后更易读的版本:

*ngIf="
    step?.salaryChangedBy?.updated
        | issalaryUpdated
        : lastViewedByUser
        : step?.salaryChangedBy?.userId
        : userId
"

这对我来说是非常奇怪的语法。有人可以告诉我这些连续的冒号在这里做什么?顺便说一下,issalaryUpdated 是一个管道。

我尝试在Angular文档和互联网上搜索,但找不到有用的信息。有人可以给我一些启发吗?谢谢!

英文:

For example:

*ngIf="step?.salaryChangedBy?.updated | issalaryUpdated : lastViewedByUser : step?.salaryChangedBy?.userId : userId"

Or the formatted one is more readable:

*ngIf="
    step?.salaryChangedBy?.updated
        | issalaryUpdated
        : lastViewedByUser
        : step?.salaryChangedBy?.userId
        : userId
"

Very strange syntax for me. Can anybody tell me what these consecutive colons do here? BTW, issalaryUpdated is a pipe.

I tried to google the Angular documentation and posts on internet and found no useful information. Can anybody shed some light on me? Thanks!

答案1

得分: 1

在你的代码示例中,issalaryUpdated 是一个管道,接受四个参数并返回一个布尔值(将在 *ngIf 中进行评估)。

issalaryUpdated 管道应该如下所示:

@Pipe({ name: 'issalaryUpdated' })
export class IsSalaryUpdatedPipe implements PipeTransform {
  transform(
    updated: any,
    lastViewedByUser: any,
    salaryChangedByUserId: string,
    currentUserId: string
  ): boolean {
    // 基于涉及到的 updated、lastViewByUser、salaryChangedByUserId 和 currentId 的逻辑返回一个布尔值
  }
}

语法中的 | 表示你正在使用一个管道。

: 分隔的值是管道的参数。

关于如何使用具有多个参数的管道的更多信息,请查看此答案

英文:

In your code example, issalaryUpdated is a pipe that take four parameters and return a boolean (which will be evaluated in *ngIf)

The issalaryUpdated pipe should look like this

@Pipe({ name: 'issalaryUpdated' })
export class IsSalaryUpdatedPipe implements PipeTransform {
  transform(
    updated: any,
    lastViewedByUser: any,
    salaryChangedByUserId: string,
    currentUserId: string
  ): boolean {
    // return a boolean here based on logic involving updated, lastViewByUser, salaryChangedByUserId and currentId
  }
}

The syntax | means that you are using a pipe

The values separated by : are the parameters of the pipe

For more informations of how do pipes with multiple arguments work, look to this answer

huangapple
  • 本文由 发表于 2023年7月27日 20:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定