【问题标题】:nested Ternary condition in Angular 6Angular 6中的嵌套三元条件
【发布时间】:2026-01-17 19:10:02
【问题描述】:

我在 HTML 模板文件中有如下三元条件,

<div
*ngFor="let $m of $layer.child; let $childIndex=index"
[Latitude]="$m.latitude"
[Longitude]="$m.longitude"
[IconInfo]="$childIndex== 0 ? _iconInfo1:$childIndex== 1 ? _iconInfo 
:$childIndex== 2 ? _iconInfo2:$childIndex== 3 ? 
_trunkLocMarker1:_trunkLocMarker"></div>

在相同的条件下,我想更改 IconInfo 中特定属性的值,如下所示:

if($m.propertyValue > 1000){
  _iconInfo1.property = 'someValue';
}

在相同的三元条件下。

我尝试了类似以下的方法:

 [IconInfo] = "$childIndex== 0 ? _iconInfo1:$childIndex== 1 ? _iconInfo :$childIndex == 2 ? _iconInfo2 : ($m.totalMou > '1000' ?_iconInfo2.fontSize = '48' : _iconInfo2.fontSize = '48'): $childIndex == 3 ? _trunkLocMarker1 : _trunkLocMarker "

但我收到错误消息:

Uncaught Error: Template parse errors:
Parser Error: Bindings cannot contain assignments

请帮忙!

提前致谢

【问题讨论】:

  • 您不能在模板表达式中赋值。也许您的要求可以通过其他方式实现。您能否说明_iconInfo2.fontSize 属性的使用方式/位置?
  • 我认为您应该将您的三元组拆分成更小的语句,并将它们放入您将在模板中调用的函数中
  • @JoH:如果不手动处理更改检测,则在数据绑定中调用函数不是一个好主意。该函数会被多次触发。
  • 具有输入属性的 div 是怎么回事?如果这是针对您使用这些输入属性创建的组件,则最容易将属性传递给组件并在那里过滤(ngOnInit 或 ngOnChanges,取决于属性是否在运行时更新)
  • 格式化很重要。我没有看到任何错误,但如果格式不正确,阅读时间会太长

标签: javascript angular typescript ngfor conditional-operator


【解决方案1】:

错误提示您不能进行作业。你有两个(singe = is assignment)

$m.totalMou > '1000' ?_iconInfo2.fontSize = '48' : _iconInfo2.fontSize = '48'

注意:我真的不建议有这么多嵌套的三元条件,尤其是在模板中。他们很难跟上。您应该将该逻辑移至打字稿。

【讨论】:

    最近更新 更多