【发布时间】:2021-07-22 16:42:02
【问题描述】:
我正在 Angular 中实现搜索功能。 我正在将数组中的详细信息显示到 div 中。 我想要的是仅显示我在搜索框中键入名称的那些详细信息。 我正在尝试对数组进行过滤方法,这就是我尝试过的:
组件.ts:
import { Component, OnInit } from '@angular/core';
import { Employee } from '../Employee';
import {NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
filteredEmployees:Employee[]=[]
searchText=""
employeeList:Employee[]=
[
{
id:1,
name:"abc def",
salary:20000,
permanent:true,
department:{id:1, name:"Payroll"},
skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
dateOfBirth:new Date('01/03/2002')
},
{
id:1,
name:"ssss gggg",
salary:40000,
permanent:false,
department:{id:2, name:"Internal"},
skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
dateOfBirth:new Date('21/03/2006')
},
{
id:1,
name:"asdf zxcv",
salary:60000,
permanent:true,
department:{id:3, name:"HR"},
skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
dateOfBirth:new Date('16/05/2010')
}
];
searchKey(data:string)
{
this.searchText=data;
}
search()
{
this.filteredEmployees = this.employeeList.filter((element)=>{
return element.name.toLowerCase()==this.searchText.toLowerCase();
});
}
}
这是我的 html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<b>Employees List</b>
<br>
<br>
<div class="form-group">
<label for="search">Search</label>
<input type="text" (keyup)="search()" id="search" [(ngModel)]="searchKey(searchText)" placeholder="Find by name" ngModel>
</div>
<div class="row" *ngFor="let e of employeeList">
<div class="block" style="width:300px;height:100px;border:1px solid #000;">
<h4>{{e.name}}</h4>
<h6>₹ {{e.salary}}</h6>
<app-employee-info></app-employee-info>
</div>
<br>
<br>
</div>
</body>
</html>
我正在尝试以两种方式将searchKey 与搜索文本框绑定,并且它的keyup 事件应该调用search 函数。
搜索然后根据输入进行过滤。
但我得到这个错误:
Unexpected token '=' at column 22 in [searchKey(searchText)=$event]
还有一件事::如何将我的显示 div 连接到我的搜索框,以便它仅根据过滤结果显示??
【问题讨论】:
-
在您的输入中
[(ngModel)]="searchText"或[ngModel]="searchText" (ngModelChange)="searchKey($event)"? -
@Kitsune66 知道了,非常感谢
-
好。此外,如果您使用 ngModelChange 您可以删除 (keyUp) 并在 searchKey 方法中只需在更新当前搜索值后调用搜索。 ` searchKey(data: string) { this.searchText = data; this.search(); }`
-
<div class="row" *ngFor="let e of filteredEmployees">显示过滤的员工。如果搜索为空,则更新搜索方法以返回所有员工。
标签: angular