Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在其他元素中使用ngFor结果?_Angular_Typescript - Fatal编程技术网

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'."