angular - 如何选择性地显示共享组件的内容
问题描述
我有一个共享组件,它为其他三个组件提供内容。我需要将搜索过滤器添加到三个组件中的两个。我将代码放在共享组件中,因为这是要过滤的信息被呈现的地方。过滤工作正常,但搜索字段显示在所有三个组件上。如何选择仅在选定组件上添加搜索字段?
在主组件(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)
}
}
解决方案
您可以在共享组件上传递一个布尔变量作为输入,然后在变量上执行 ngIf 以显示搜索(如果为真),然后在父/表示组件上为您不想要的部分在输入变量上传递假显示搜索并为您要显示的搜索执行其他操作。这将解决它
推荐阅读
- reactjs - 从缓存中检索的数据被返回,但不显示在页面上
- javascript - 仅在 JavaScript 中刷新 AJAX DIV
- windows - Win Server 2019 计划任务在重启错误后仍然存在
- ruby-on-rails - 使用 Rails 6 实施 Google Adsense
- kubernetes - kubernetes 标签 node-role.kubernetes.io/master 和 node-role.kubernetes.io/control-plane 有什么区别?
- c++ - Windows 3.11 WH_MOUSE_LL 等效?
- javascript - 我可以通过重新启动按钮更改井字游戏中的 innerHTML,但是一旦重新启动,我就无法再次重新分配以开始游戏
- mfc - MFC:将 CSplitterWnd 应用到我的 CChildFrame 后,主窗口标题不再更新
- node.js - socket.io Typescript 无法创建服务器,“此表达式不可调用”
- android - 涉及 MutableSharedFlow 的测试 - java.lang.IllegalStateException:此作业尚未完成