我确定我会在这里使用:facepalm,但是在从Angular 7升级到9的过程中,这似乎已经停止了。
我想有条件地显示属性(car.type
),如果它不是空字符串:
<select class="form-control" [(ngModel)]="selections.modelId">
<option *ngFor="let car of selections.possibleCars" [value]="car.modelId" >
<span *ngIf="car?.type">{{car.type}} - </span>{{ car.modelName }}
</option>
</select>
这曾经用来显示car.type
(例如“卡车”),但现在不再显示。如果删除*ngIf
子句,则会得到car.type
的值,它是一个非零长度的字符串。
奇怪的是,它显示在标记中,而不显示在实际页面上!实际上,使用下面的模拟数据,如果我将“ DCT111”更改为“ DCT112”,则会显示“蝙蝠侠-”!但是奇怪的是,如果我将“蝙蝠侠”更改为其他名称,它将保持隐藏状态。这是怎么回事?
另外,如果我删除
<!--bindings
注释,则会显示“蝙蝠侠”。如果我更改“蝙蝠侠”(再次在Chrome devtools中使用),则它不会显示。
我什至在单击时都在页面上挂了一个按钮来运行“更改检测”,但这并没有使它显示出来。
答案 0 :(得分:3)
这可能无法解决您的问题,但可能会对您有所帮助。首先,对象foo
是未定义的,您正在从API获取数据。
尝试在*ngIf()
中进行可选链接:
<span *ngIf="foo?.bar">{{foo.bar}} - </span>{{ foo.otherBar }}
或者您也可以尝试:
<span *ngIf="foo && foo.bar">{{foo.bar}} - </span>{{ foo.otherBar }}
如果foo
对象为null
,则访问bar
成员将引发错误。
您提供的代码没有问题。可能是其他原因造成的。
如果有帮助,请尝试检测更改:
constructor(private cd: ChangeDetectorRef){}
// After assigning value to the object in the API call.
this.cd.detectChanges()
根据MDN,选项标记中仅允许文本。将<span>
替换为<ng-container *ngIf...>
。
在此处查看更多信息: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option