角度4:匹配事件中的嵌套json项目值与其他对象中的相同项目值相匹配
问题描述:
我正在使用角度4的应用程序。 我是Angular的初学者。 我需要2个东西帮助:角度4:匹配事件中的嵌套json项目值与其他对象中的相同项目值相匹配
- 第一:当我在HTML点击一个用户名,我想匹配的名称与所有对象相同的用户名是出现在点击
第二种:显示这个用户名所在的书的标题。
例如:当我点击Jose Miguel时,我想在HTML上看到他读过的2本书。
JSON数据:
books = [
{
"title": "title1",
"author": "author1",
"users": [
{
"id": 1,
"name": "Isidro"
},
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 3,
"name": "Trinidad"
}
]
},
{
"title": "title2",
"author": "author2",
"users": [
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 5,
"name": "Beatriz"
},
{
"id": 6,
"name": "Rosario"
}
]
},
HTML:
<div style="text-align:center">
<ul class="books">
<li *ngFor="let book of books" >
Título: {{book.title}} <br> Autor: {{book.author}}<br>
<ul style="text-align:center" class="recentUsers">
<li *ngFor="let user of book?.users" (mouseenter)="myEvent($event)" class="individualUsers">{{user.name}}</li>
</ul>
</li>
</ul>
</div>
到这里我设法显示所有书籍和阅读了每一个特定的书,最近的用户。 (mouseenter)=“myEvent($ event)”只是控制台日志记录,正如你可以预测的那样,第一本书的第一个用户的名字,但这不是我所需要的。 这是我需要帮助的部分。
import { Component, OnInit } from '@angular/core';
import { BooksService } from '../books.service';
@Component({
selector: 'app-completo',
templateUrl: './completo.component.html',
styleUrls: ['./completo.component.css']
})
export class CompletoComponent implements OnInit {
constructor(private booksService: BooksService){
}
books = [];
ngOnInit(){
this.booksService.getBooks().subscribe(responseBooks => this.books =responseBooks);
}
myEvent(){
console.log(this.books[0].users[0].name)
event.preventDefault();
}
}
答
你可以简单地筛选图书清单已在事件:
readBooks: Array;
// ...
showReadBooksForUser(userId: number) {
readBooks = books.filter(
(book) => book.users.findIndex((user) => user.id == userId) > -1
);
}
resetReadBooks() {
readBooks = null;
}
也许类似的东西在你的HTML:
<div style="text-align:center">
<ul class="books">
<li *ngFor="let book of books" >
Título: {{book.title}} <br> Autor: {{book.author}}<br>
<ul style="text-align:center" class="recentUsers">
<li *ngFor="let user of book?.users"
(mouseenter)="showReadBooksForUser(user.id)"
(mouseleave)="resetReadBooks()"
class="individualUsers">{{user.name}}</li>
</ul>
</li>
</ul>
<!-- display book div with appropriate css? -->
<div *ngIf="readBooks" id="readBooksOverlay">
<ul>
<li *ngFor="let book of readBooks">{{book.title}}</li>
</ul>
</div>
</div>
非常感谢您的帮助! 我不得不做一些改变: readBooks:Array; showReadBooksForUser(userId:number){ \t this.readBooks = this.books.filter( (book)=> book.users.findIndex((user)=> user.id == userId)> -1); } resetReadBooks(){ this.readBooks = null; } –