【发布时间】:2022-01-10 01:53:24
【问题描述】:
我有一个正在显示的对象列表,我添加了一个搜索框来过滤列,现在当我输入一个值时,它工作正常并且数据被过滤。问题是,当我清除搜索框时,我没有取回所有数据,我一直停留在我首先搜索的内容上,所以每次我想更改输入的值或获取整个列表时都必须刷新。
这是我的 Ts 代码:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Facture } from '../model/facture.model';
import { FactureService } from '../services/facture.service';
@Component({
selector: 'app-factures',
templateUrl: './factures.component.html',
styleUrls: ['./factures.component.css']
})
export class FacturesComponent implements OnInit {
factures?: Facture[]; //un tableau de chînes de caractères
cat?: number;
constructor(private factureService: FactureService, private router: Router) {
// this.factures = factureService.listeFacture();
}
deleteFacture(p: Facture) {
let conf = confirm("Etes-vous sûr ?");
if (conf)
this.factureService.deleteFacture(p.idFacture).subscribe(() => {
console.log("facture supprimé");
});
this.router.navigate(['factures']).then(() => {
window.location.reload();
});
}
search() {
if (this.cat != null) {
this.factures = this.factures?.filter(res => {
return res.idFacture.toLocaleString().match(this.cat!.toLocaleString())
});
} else if (this.cat == null) {
this.ngOnInit();
}
}
ngOnInit(): void {
this.factureService.listeFacture().subscribe(prods => {
console.log(prods);
this.factures = prods;
});
}
}
这是我的 HTML 代码:
<body >
<main role="main" class="container" >
<div class="jumbotron" style="background-color: white;">
<h2>Liste des Adhérents</h2>
<input type="text" [(ngModel)]="name" (input)="Search()" />
<table class="table table-hover">
<thead class="thead-light">
<tr>
<th>Nom Complet</th>
<th>Grade</th>
<th>Poste</th>
<th>Telephone</th>
<th>E-mail</th>
<th></th>
</tr>
</thead>
<tr *ngFor="let item of adherents">
<td>{{item.nomcomplet}}</td>
<td>{{item.grade}}</td>
<td>{{item.poste}}</td>
<td>{{item.telephone}}</td>
<td>{{item.email}}</td>
<td><button [routerLink]="['/adherents/', item.id]" style="margin-right: 0.2em;" title="Details" class="btn-sm btn-secondary text-white"><i class="fa fa-eye"></i></button>
<button [routerLink]="['/adherentEdit/', item.id]"
style="margin-right: 0.2em;" title="Modifier" class="btn-sm btn-primary text-white"><i class="fa fa-edit"></i></button></td>
</tr>
</table>
</div>
</main>
</body>
请问如何修改 Search() 函数,以便在更改搜索框输入中的值时从数组中动态获取数据?
【问题讨论】:
-
您正在过滤原始数组并将其分配回原始数组,因此这是意料之中的。您需要第二个数组来存储原始值。虽然我个人喜欢在模板中使用 formcontrol 和异步管道来过滤 observables。只是我的喜好。
-
哦...
this.factures在哪里使用...?注意到刚才,您似乎在模板中使用了一个不相关的数组?