【问题标题】:Show the table only when I looked for 3 characters仅在我查找 3 个字符时显示表格
【发布时间】:2019-09-21 17:48:00
【问题描述】:

我使用 angular、angular-material 和 firebase。

我可以使用下面的代码正确显示我的数据、过滤、排序和分页。

只有当我已经在搜索栏中输入 3 个字符时,我才会显示我的数据。

你能帮我或给我一个轨道吗?谢谢!

export class AnnuairePSComponent implements OnInit {

Data = {
titre:'',
prenom: '',
nom:'',
prof: '',
sv: '',
site:''
}

displayedColumns = [
'titre',
'prenom',
'nom',
'prof',
'sv',
'site'
 ];

 dataSource = new MatTableDataSource();

applyFilter(filterValue: string) {
filterValue = filterValue.trim(); 
filterValue = filterValue.toLowerCase(); 
this.dataSource.filter = filterValue;
}

ngAfterViewInit() {
this.psService.getpss().subscribe(res => {this.dataSource.data = res;}); 
}

private paginator: MatPaginator;
private sort: MatSort;

@ViewChild(MatSort) set matSort(ms: MatSort) {
this.sort = ms;
this.setDataSourceAttributes();
}

@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
this.paginator = mp;
this.setDataSourceAttributes();
}

setDataSourceAttributes() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}

constructor(private psService: PsService, private router: Router) { }
}

html

<mat-toolbar color="primary" [ngStyle]="{'height': '120px','padding-top' :'30px'}"> 

<mat-form-field appearance="outline" style="width:100%" >
<input matInput (keyup)="applyFilter($event.target.value)"  >
<mat-label>Rechercher un professionel</mat-label>
</mat-form-field>

<span class="example-spacer"></span>
</mat-toolbar>

<mat-card [ngStyle]="{'margin': '5px'}" *ngIf="dataSource?.filteredData.length">

<mat-table  [dataSource]="dataSource" [ngStyle]="{ 'width':'100%'}" matSort>
.....
</mat-table>

【问题讨论】:

  • 您希望仅在输入 3 个或更多字符时进行过滤吗?

标签: angular filter angular-material mat-table


【解决方案1】:

你试过了吗:

applyFilter(filterValue: string) {
    if (filterValue.length > 3) {
        filterValue = filterValue.trim(); 
        filterValue = filterValue.toLowerCase(); 
        this.dataSource.filter = filterValue; 
    }
}

编辑:好的,所以您应该在模板的局部变量中注册您的输入:

 <input matInput (keyup)="applyFilter($event.target.value);" #filterInput >

然后在您的表格上应用结构指令:

<mat-table  [dataSource]="dataSource" [ngStyle]="{ 'width':'100%'}" matSort *ngIf="filterInput.value.length > 3">

【讨论】:

  • 加载组件时我的表格仍然可见。我应该修改html中的一些东西吗?
  • 好吧,我不明白,我不是那样理解的。我刚刚更新了我的答案。
【解决方案2】:

每次需要时都编写过滤逻辑可能不是一个好习惯。如果您需要更多表和过滤器,那么您最终将重复代码。我建议创建一个用于过滤的指令或使用已经为角度材料创建的指令:mat-table-filter

我最近为我的项目创建了这个库,并决定发布以供社区使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多