首页 > 解决方案 > 如何选择性地显示共享组件的内容

问题描述

我有一个共享组件,它为其他三个组件提供内容。我需要将搜索过滤器添加到三个组件中的两个。我将代码放在共享组件中,因为这是要过滤的信息被呈现的地方。过滤工作正常,但搜索字段显示在所有三个组件上。如何选择仅在选定组件上添加搜索字段?

在主组件(employee.html)中我使用的是共享组件(列表)

 <app-list [model]="cards" 
           [emptyMessage]="No Employee"></app-list>

在列表组件中。我添加了搜索框并将搜索过滤器应用于显示员工姓名的 for 循环

<mat-form-field class="search-field">
<ng-content></ng-content>
<mat-icon>search</mat-icon>
<input autofocus matInput #searchTermInput type="search"
     [(ngModel)]="searchTerm" >
</mat-form-field>

//应用搜索过滤器

<div class="empty-view" *ngIf="model && model.length === 0">
{{ emptyMessage }}</div>

<mat-card *ngFor="let item of model | searchFilter:searchTerm">

搜索过滤器管道

import {Pipe, PipeTransform} from '@angular/core';
import {Card} from "./card";

@Pipe({
name:'searchFilter'
})
export class SearchFilterPipe implements PipeTransform{
transform(model: Card<any>[], searchTerm:string):Card<any>[]
{
if(!model || !searchTerm){
  return model
}
return model.filter(item 
=>item.title.toLowerCase().indexOf(searchTerm.toLowerCase())!== -1)
}
}

标签: angularcomponents

解决方案


您可以在共享组件上传递一个布尔变量作为输入,然后在变量上执行 ngIf 以显示搜索(如果为真),然后在父/表示组件上为您不想要的部分在输入变量上传递假显示搜索并为您要显示的搜索执行其他操作。这将解决它


推荐阅读