如何在Angular 5(TypeScript)的对象数组中展示特定对象
没问题,我来一步步帮你搞定在Angular 5里展示对象数组中特定对象的需求~
第一步:完善你的DataProvider
目前你的DataProvider只有私有数组,我们需要添加方法来暴露数据(包括获取特定对象的方法),这样组件才能调用到数据。修改后的代码如下:
export class DataProvider { private locations: any[] = [ { "name": "restaurant", "location": "downtown", "category": "restaurant", "id": "1" }, { "name": "law firm", "location": "center city", "category": "office", "id": "2" }, { "name": "public library", "location": "suburb", "category": "library", "id": "3" } ]; // 获取所有地点数据 getLocations(): any[] { return this.locations; } // 根据ID获取单个特定地点 getLocationById(id: string): any | undefined { return this.locations.find(location => location.id === id); } // 可选:根据分类获取一组特定地点 getLocationsByCategory(category: string): any[] { return this.locations.filter(location => location.category === category); } }
第二步:在组件中注入DataProvider并获取数据
你需要在对应的组件里注入这个DataProvider,把需要的数据赋值给组件的属性,这样HTML模板才能访问到。示例组件代码:
import { Component, OnInit } from '@angular/core'; import { DataProvider } from './data-provider'; // 请根据你的实际文件路径调整 @Component({ selector: 'app-locations', templateUrl: './locations.component.html', providers: [DataProvider] // 确保DataProvider被注入到组件中 }) export class LocationsComponent implements OnInit { locations: any[]; selectedSingleLocation: any; // 用来存储单个特定对象 constructor(private dataProvider: DataProvider) { } ngOnInit(): void { // 1. 获取所有地点(如果需要遍历全量数据) this.locations = this.dataProvider.getLocations(); // 2. 获取单个特定对象,比如ID为"2"的律所 this.selectedSingleLocation = this.dataProvider.getLocationById("2"); // 3. 可选:获取某一类别的所有对象,比如所有餐厅 // this.locations = this.dataProvider.getLocationsByCategory("restaurant"); } }
第三步:在HTML模板中展示数据
根据你的需求,分两种常见场景处理:
场景1:展示单个特定对象
如果只想展示某一个特定对象(比如上面的selectedSingleLocation),直接在模板中绑定属性即可,记得用*ngIf避免数据未加载时的报错:
<div *ngIf="selectedSingleLocation"> <h1>{{ selectedSingleLocation.name }}</h1> <h2>{{ selectedSingleLocation.location }}</h2> </div>
场景2:展示过滤后的一组特定对象
如果你还是想用*ngFor遍历,但只展示符合条件的对象,推荐在组件中提前过滤数据(性能更好),然后模板直接遍历处理后的数组:
<!-- 这里的locations已经是组件中过滤好的特定组数据 --> <div *ngFor="let location of locations"> <h1>{{ location.name }}</h1> <h2>{{ location.location }}</h2> </div>
如果只是临时在模板中简单过滤(不推荐复杂场景使用),可以直接用*ngIf嵌套判断:
<div *ngFor="let location of locations" *ngIf="location.category === 'restaurant'"> <h1>{{ location.name }}</h1> <h2>{{ location.location }}</h2> </div>
另外,如果你想在遍历全量数据时突出显示某个特定对象,可以用条件样式:
<div *ngFor="let location of locations" [class.highlighted]="location.id === '1'"> <h1>{{ location.name }}</h1> <h2>{{ location.location }}</h2> </div>
然后在组件的CSS里定义.highlighted的样式(比如背景色变浅)即可。
内容的提问来源于stack exchange,提问作者jamesharvey
相关产品推荐
相关产品推荐

