Angular2中Titlecase管道与三元运算符配合失效问题咨询
Great question! The issue here boils down to operator precedence in Angular's template syntax—let's break this down step by step.
The Root Cause: Operator Precedence
In Angular templates, the pipe operator (|) has higher precedence than the ternary conditional operator (?:). That means your original code:
<span>{{item.value == 'user' ? 'student' : item.value | titlecase}}</span>
Is actually being evaluated like this:
<span>{{item.value == 'user' ? 'student' : (item.value | titlecase)}}</span>
Notice the implicit parentheses around item.value | titlecase? The pipe is only being applied to the else branch of your ternary operator. When item.value is 'user', the code returns the raw string 'student' with no pipe processing—hence why it stays lowercase unless you manually capitalize it.
The Fix: Wrap the Ternary in Parentheses
To make the TitleCase pipe apply to the entire result of the ternary operator (both the 'user' → 'student' conversion and the original values like 'admin'/'editor'), you just need to wrap the whole ternary expression in parentheses. This forces Angular to evaluate the ternary first, then apply the pipe to its output.
Here's the corrected code:
<div class="dashboard-table-item row" *ngFor="let item of itemArray"> <span>{{(item.value == 'user' ? 'student' : item.value) | titlecase}}</span> </div>
How It Works Now
- When
item.valueis'user': The ternary returns'student', which then gets passed through TitleCase to become'Student'. - When
item.valueis'admin'or'editor': The ternary returns the original value, which is then TitleCased to'Admin'and'Editor'(just like your original code did for these cases).
This achieves exactly what you want—no changes to itemArray, and consistent TitleCase formatting across all values.
内容的提问来源于stack exchange,提问作者T04435

