我有两个数组:categories
和articles
。
这里是数组的样子:
categories = [{id: 1, name: 'Gadgets'}, {id: 2, name: 'Artificial Intelligence'}, {id: 3, name: 'Opinions'}];
articles = [{id: 1, categoryId: 3, title: 'Title 1', body: 'Body Text 1'}, {id: 2, categoryId: 1, title: 'Title 2', body: 'Body Text 2'}, {id: 3, categoryId: 1, title: 'Title 3', body: 'Body Text 3'}];
在以下新闻Feed中,categoryId
需要由category.name
替换。我如何从数组中获取所需的对象,以便我可以访问其name属性 - 而无需遍历视图中的categories
数组?
我想在模板中执行类似{{category(article.categoryId).name}}
的操作,但语法不正确。
Template:
<div class="col-md-8">
<h4>{{article.title }}</h4>
<p>{{article.body }}</p>
<div class="tag tag-default">
CategoryId: {{article.categoryId}} <!-- Need category.name -->
</div>
<div class="tag tag-success">
Published: {{article.date_publish | date:'medium'}}
</div>
<div class="tag tag-info">
Created: {{article.date_created | date:'medium'}}
</div>
</div>
ArticlesComponent
articles: Article[];
categories: Category[];
constructor(
private _articleService: ArticleService,
private _categoryService: CategoryService,
) {}
ngOnInit()
{
this._articleService.getArticles().subscribe(articles => {this.articles = articles});
this._categoryService.getCategories().subscribe(categories => {this.categories = categories});
}
答案 0 :(得分:1)
您可以在html中调用一个函数来提取类别名称
<div class="col-md-8">
<h4>{{article.title }}</h4>
<p>{{article.body }}</p>
<div class="tag tag-default">
CategoryId: {{categoryname(article.categoryId)}} <!-- Need category.name -->
</div>
<div class="tag tag-success">
Published: {{article.date_publish | date:'medium'}}
</div>
<div class="tag tag-info">
Created: {{article.date_created | date:'medium'}}
</div>
</div>
并在您的组件中,您可以在this.categories
中搜索它 articles: Article[];
categories: Category[];
constructor(
private _articleService: ArticleService,
private _categoryService: CategoryService,
) {}
ngOnInit()
{
this._articleService.getArticles().subscribe(articles => {this.articles = articles});
this._categoryService.getCategories().subscribe(categories => {this.categories = categories});
}
categoryname(id: string){
console.log(id);
return this.categories[id];// add your code here if your array syntax is different, you can use lodash also
}
我认为你也可以使用{{categories[article.categoryId]}}
如果你的数组很简单并将html部分放在*ngIf
中以防止未定义的错误