我在视图中有一个简单的列表,控制器中有硬编码的数据:
errorcount.component.html
...
<tr *ngFor="let errorcounter of errorCounterList">
<td>{{errorcounter.date}}</td>
<td style="text-align:right;">{{errorcounter.count}}</td>
</tr>
....
errorcount.component.ts
import { Component, OnInit, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
export interface ErrorCounter {
id: number,
error_id: number,
date: string,
count: number
};
@Component({
selector: 'app-errorcount',
templateUrl: './errorcount.component.html',
styleUrls: ['./errorcount.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ErrorcountComponent implements OnInit {
errorCounterList: ErrorCounter[];
constructor(private ref: ChangeDetectorRef) {
this.errorCounterList = [
{ id: 1, error_id: 1, date: '20230101', count: 201 },
{ id: 2, error_id: 2, date: '20230102', count: 321 },
{ id: 3, error_id: 3, date: '20230103', count: 431 },
{ id: 4, error_id: 1, date: '20230104', count: 541 },
{ id: 5, error_id: 2, date: '20230105', count: 651 },
{ id: 6, error_id: 3, date: '20230106', count: 561 },
{ id: 7, error_id: 1, date: '20230107', count: 471 },
{ id: 8, error_id: 2, date: '20230108', count: 381 },
{ id: 9, error_id: 3, date: '20230109', count: 282 },
{ id: 10, error_id: 1, date: '20230110', count: 184 },
];
}
ngOnInit(): void {
this.ref.detectChanges();
}
filterCounters(id: number) {
this.errorCounterList = this.errorCounterList.filter(f => f.error_id == id);
this.ref.markForCheck();
}
}
我调用filterCounters(),调试器显示过滤列表,但detectChanges不改变视图中的项。
任何帮助都会让我再次入睡。
我已经准备好在下面的stackblitz链接中复制您的应用程序:
https://stackblitz.com/edit/my-angular-project-wdllee?file=app/login/login.component.ts
效果很好,你需要调用你的过滤器函数:
ngOnInit(): void {
this.ref.detectChanges();
this.filterCounters(1); // => You need call your function
}
你不需要"ChangeDetectionStrategy.OnPush
";如果你只在需要刷新视图时调用你的函数会更好。
请阅读这篇文章:
https://stackoverflow.com/a/53426605/9420442
对于它可能有所帮助的人,我得到这个工作的唯一方法是使用LocalStorage:
ngOnInit(): void {
localStorage.setItem('errorCounterList', JSON.stringify(this.errorCounterList));
}
filterCounterList(id: number) {
localStorage.removeItem('errorCounterList');localStorage.setItem('errorCounterList',JSON.stringify(this.errorCounterList.filter(f => f.error_id == id)));
}
getCounterList() {
this.errorCounterList = JSON.parse(localStorage.getItem('errorCounterList') ?? '');
return this.errorCounterList;
}
这解决了我的直接问题,但它并不总是适合作为一个解决方案。