Angular 如何在其他元素中使用ngFor结果?
我使用此模板按Angular 如何在其他元素中使用ngFor结果?,angular,typescript,Angular,Typescript,我使用此模板按ngFor打印搜索结果,并在列表之前进行结果计数: Found 1 result for **test** test title 模板: <div class="container"> <div [ngSwitch]="resultCounter"> <h6 class="my-5" *ngSwitchCase="'0'">There is no data about {{ searchedPhrase }}!<
ngFor
打印搜索结果,并在列表之前进行结果计数:
Found 1 result for **test**
test title
模板:
<div class="container">
<div [ngSwitch]="resultCounter">
<h6 class="my-5" *ngSwitchCase="'0'">There is no data about {{ searchedPhrase }}!</h6>
<h6 class="my-5" *ngSwitchCase="'1'">Found {{ resultCounter }} result for <strong>{{ searchedPhrase }}</strong></h6>
<h6 class="my-5" *ngSwitchDefault>Found {{ resultCounter }} results for <strong>{{ searchedPhrase }}</strong></h6>
</div>
<ul class="search-result">
<li *ngFor="let item of dataset | searchFilter:searchedPhrase:'title' as total; index as i" class="py-2">
<p [title]="getResultCount(i)">{{ item.title }}</p>
</li>
</ul>
</div>
但是我得到了这个错误,这意味着传递超出*ngFor范围的数据的方法是错误的:
ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngSwitch: undefined'. Current value: 'ngSwitch: 1'."
第一次
resultCounter
值未定义,因此您必须在this.resultCounter=0中传递默认值
使用此项检查从组件中删除resultCounter并获取resultcount。在模板中使用i+1
了解当前索引,使用total.length
了解筛选结果的数量。您不能在ngFor的每次迭代中都尝试修改组件的状态。我同意您关于total.length的评论,但关于删除getResultCount函数,因为要访问超出其作用域的ngFor
数据,最好通过typescript传递它。目前,传递过程工作正常,但主要问题是ngFor
过程一直持续到最后一项,并在第一次打印后更新resultCounter
ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngSwitch: undefined'. Current value: 'ngSwitch: 1'."