Angular:ngIf 不适用于 object.property

Angular: ngIf not working for object.property

我确定我会在这里使用 :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(例如 "Truck"),但现在不行了。如果我删除 *ngIf 子句,我会得到 car.type 的值,它是一个非零长度字符串。

奇怪的是它显示在标记中,但没有显示在实际页面上!事实上,使用下面的模拟数据,如果我将 "DCT111" 更改为 "DCT112",那么 "Batman - " 就会出现!但奇怪的是,如果我将 "Batman" 更改为其他内容,它会保持隐藏状态。这是怎么回事? 此外,如果我删除 <!--bindings 评论,则会显示 "Batman"。如果我更改 "Batman"(同样,只是在 Chrome devtools 中),那么它不会显示。 我什至在页面上连接了一个按钮 运行 单击它时更改检测,但这并没有使它显示出来。

这可能无法解决您的问题,但可能会对您有所帮助。起初,对象 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