【发布时间】:2020-04-04 20:44:30
【问题描述】:
我在 ngfor 中有一个嵌套的 ngif:
<ion-content>
<ng-container *ngFor="let item of (results | async)">
<ng-container *ngFor="let elements of item.bc; first as isFirst; index as i">
<ng-container *ngIf="elements.Event.StartTime >= '2019-12-11T15:00:00' ?func():false">
<ion-item>{{elements.Event.StartTime | date:'shortTime'}}</ion-item>
</ng-container>
</ng-container>
</ng-container>
</ion-content>
我从这里看到了带有函数的分辨率:Show only first match from *ngIf expression
export class Tab4Page implements OnInit {
results: Observable<any>;
isFirstMatch = false;
constructor(private channel: Service) {
}
func() {
if (this.isFirstMatch === false) {
this.isFirstMatch = true;
return true;
} else {
return false;
}
}
ngOnInit() {
this.results = this.channel.searchData();
}
}
但这对我不起作用。我收到此错误:
ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf: true'。当前值:'ngIf: false'。
有没有更好的方法只输出第一个匹配项?或者如果没有,请告诉我应该如何修复 ExpressionChanged 错误。
【问题讨论】:
-
为什么不在模板中使用数据之前按照您的意愿构建数据并摆脱不必要的黑客攻击?在这种情况下,您可以订阅 observable/using map 运算符在此处进行过滤,而不是尝试在 html 中使用
break。 -
谢谢,洋柴! :)
标签: angular ngfor angular-ng-if