这是(custom.component.html)文件
<input type="text" [(ngModel)]="name" (ngModelChange)="onNameChange()">
<div *ngFor="let s of filteredScreenshots">
{{s | json}}
</div>
<mat-card class="example-card" *ngFor="let filteredScreen of
filteredScreens" let i = index>
<mat-card-header>
<div mat-card-avatar class="example-header-image" >
<img mat-card-image class="list-img" src="{{filteredScreen?.img}}" >
</div>
<mat-card-content class="names"><b>{{ filteredScreen?.name }}</b></mat-card-content>
</mat-card-header>
</mat-card>
这是(customer.component.ts)
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/operators'
import * as _ from 'lodash';
@Component({
selector: 'ylb-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent {
spaceScreens: Array<any>;
filteredScreens = [];
name: string;
constructor(private http:Http){
this.http.get('assets/app.json').pipe(
map(response => response.json().screenshots)
)
.subscribe(res => {
this.spaceScreens = this.sortByName(res); //this is what we filter against
this.filteredScreens = this.sortByName(res);//init with full list
});
}
onNameChange() {
this.filteredScreens=_.filter(this.spaceScreens,(item)=>{
console.log(this.name)
return item.name.toLowerCase().indexOf(this.name.toLowerCase())>-1;
});
}
sortByName = function(users) {
const byName = function(user1,user2) {
return user1.name.localeCompare(user2.name);
};
return users.slice().sort(byName);
};
}
这是资产文件夹中存在的(app.json)json文件
{
"screenshots":[
{
"img":"assets/img/json_2.jpg",
"name":"Virat Kohli"
},
{
"img":"assets/img/json_2.jpg",
"name":"Joe Root"
}
]
}
过滤进行得很好,并按字母顺序显示json数据(名称)。我想突出显示在字段中输入的文本,例如在移动联系人列表中,就像在附件图像中一样。
尝试了很多资源但没有结果
答案 0 :(得分:1)
在Chrome和其他浏览器中(请参见here),您可以使用以下组件:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
transform(value: string, args: string): any {
if (args && value) {
value = String(value); // make sure its a string
const startIndex = value.toLowerCase().indexOf(args.toLowerCase());
if (startIndex !== -1) {
const matchingString = value.substr(startIndex, args.length);
return value.replace(matchingString, "<mark>" + matchingString + "</mark>");
}
}
return value;
}
}
要这样使用:
<mat-card-content class="names"><b [innerHTML]="filteredScreen.name | highlight: name"></b></mat-card-content>
答案 1 :(得分:0)
Joniras的回答很好...但是我发现这个问题太普遍了,几乎没有可定制性和可访问性(例如选择,双击,适当的聚焦/模糊等)。我发布了一个快速的组件,可以帮助您那个。
希望它也可以帮助其他人!