angular - 过滤异步数据并将数据反映到表中
问题描述
语境
我正在 Angular 11 中创建一个 Web 应用程序,并且我正在使用从特定后端服务器接收到的异步数据。我从后端接收数据并订阅它,以便它反映到我的表格视图中。现在我想实现一个基于某个谓词(在本例中为行名)进行过滤的过滤器功能。
问题陈述
当我尝试在过滤后的列表中进行更改时会出现问题,一旦过滤完成并删除文本输入表单中的谓词,该表将由“this.ngOnInit()”函数重新填充。它不包含对对象所做的任何更改,因为它再次从后端服务器重新加载。
问题源代码:
components: Comp[] = [];
searchComponent: any
ngOnInit(): void {
this.load();
}
private load(): void {
this.componentService.getComponents().subscribe(component => {
this.components = component;
}, error => {
console.error(`${error}`);
});
}
searchAvailable(): void {
if (this.searchComponent === '') {
this.ngOnInit();
} else {
this.components = this.components.filter(comp => {
return comp.Komponente.toLocaleLowerCase().match(this.searchComponent.toLocaleLowerCase());
}
}
演示代码:
<input type="text" class="form-control" placeholder="Filter"
[(ngModel)]="searchComponent"
(ngModelChange)="searchAvailable()" #filter>
表格填充:
<tr *ngFor="let component of components>
我正在寻找的结果:
我的目标是能够根据给定的谓词过滤可观察列表,在收到的列表中进行一些更改并将其合并回原始列表中,以便查看表中的列表。
解决此问题并将正确数据保存到表中的方法是什么?预先感谢!
解决方案
我为您创建了一个示例应用程序,请在此处查看完整的工作示例
所以最终的代码看起来像这样,希望它有所帮助。
import { Component } from '@angular/core';
import { Comp } from './component.model';
import { ComponentService } from './component.service';
interface VComp extends Comp {
isVisible: boolean;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
components: VComp[] = [];
query: string;
constructor(private componentService: ComponentService) {
this.load();
}
private load(): void {
this.componentService.getComponents().subscribe(
component => {
this.components = component.map(c => {
return { ...c, isVisible: true };
});
},
error => {
console.error(`${error}`);
}
);
}
doSearch(): void {
if (!this.query) {
this.components.forEach(c => (c.isVisible = true));
return;
}
this.components.forEach(c => {
const match = c.name.match(new RegExp(this.query, 'i')); // for case insensitive search
c.isVisible = !!match;
});
}
}
推荐阅读
- mysql - 触发器将所有已售商品的价格和输出添加到发票表
- c - 如何用C中的另一个字符串替换字符串中的子字符串?
- ios - '? 中的结果值 :' 表达式的类型不匹配 'some Gesture'
- r - 如何在 R 中将面板数据转换为正确的形式
- oracle - 嵌套脚本的 SQLplus 错误处理
- r - 如何在 R 中对这些类型的数据取平均值
- javascript - 使用 JavaScript 打印隐藏的表格
- objective-c - 无法在 iOS 上为 arm64 构建 WebRTC
- python - 创建日期等于原始日期的 +1 天的重复行
- python - 使用循环在 file2 中从 file1 中搜索名称并写入 file3