我有两个json文件:
test.json
[{
"id": 1,
"name": "Home"
},
{
"id": 2,
"name": "Test"
}
]
test2.json
[{
"id-cat": 2,
"name": "Test 1"
},
{
"id-cat": 1,
"name": "Test 2"
}
]
form.component.ts
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { ButtonComponent } from '../atomic/button.component';
@Component({
templateUrl: 'form.component.html',
styleUrls: ['form.component.scss']
})
export class FormComponent {
data: Object[];
data2: Object[];
constructor(private http: Http) {
this.http.get('../assets/data/test.json')
.subscribe(res => this.data = res.json());
}
private loadComponent = false;
loadMyChildComponent(id: Number) {
// missing code
this.loadComponent = true;
}
}
form.component.html
<ul>
<li *ngFor="let d of data" (click)="loadMyChildComponent(d.id);">
{{ d.name }}
</li>
</ul>
<div *ngIf="loadComponent">
<ul>
<li *ngFor="let x of data2">
{{ x.id-cat }}
</li>
</ul>
</div>
当我点击第一个列表时,我想根据传入的id加载 test2.json 数据。与此文件的id-cat相同。
如何绑定它?
答案 0 :(得分:0)
你可以这样做:
[{
"idcat": 2,
"name": "Test 1"
},
{
"idcat": 1,
"name": "Test 2"
}]
<ul>
<li *ngFor="let d of data" (click)="loadMyChildComponent(d.id);">
{{ d.name }}
</ul>
<div *ngIf="loadComponent">
<ul>
<li *ngFor="let x of data2">
{{ x.idcat }}
</li>
</ul>
</div>
export class FormComponent {
data: Object[];
data1: Object[];
data2: Object[];
constructor(private http: Http) {
this.http.get('../assets/data/test.json')
.subscribe(res => this.data = res.json());
this.http.get('../assets/json/test2.json')
.subscribe(res => this.data1 = res.json());
}
private loadComponent = false;
loadMyChildComponent(id: Number) {
// missing code
this.loadComponent = true;
this.data2 = this.data1.filter(res => res['idcat'] == id)
}
}