How to get .json objects by id in Angular 2?
How to get .json objects by id in Angular 2?
I'm trying to get objects by id from a JSON file after selecting an item from my drop-down list. So far I have managed to retrieve all the objects from JSON but not by ID.
Typescript
showInfo()
var selected = this.diadikasies.filter(x=> x.content);
console.log (selected);
HTML
<div *ngIf="diadikasies && diadikasies.length > 0" class="form-group">
<label for="diadikasies">
<i class="fas fa-clipboard-list" aria-hidden="true"></i> Please Select: </label>
<select #proc (change)="showInfo()">
<option [ngValue]="undefined" disabled selected>Επιλέξτε Διαδικασία</option>
<option *ngFor="let diad of diadikasies" [value]="diad.id"> diad.title.rendered </option>
</select>
</div>
Thanks in advance.
2 Answers
2
You can do with find() method like below
find()
TS file
import Component from '@angular/core';
@Component(
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
)
export class AppComponent
name = 'Angular';
description;
opts = [
id: 1,
name: 'Test 1',
description: 'This is Test 1 description'
,
id: 2,
name: 'Test 2',
description: 'This is Test 2 description'
];
showInfo(value)
let selectedOpt = this.opts.find(opt => opt.id == value);
this.description = selectedOpt.description;
In the template file
<div *ngIf="opts && opts.length > 0" class="form-group">
<label for="opts">
<i class="fas fa-clipboard-list" aria-hidden="true"></i> Please Select: </label>
<select #proc (change)="showInfo(proc.value)">
<option [ngValue]="undefined" disabled selected>Επιλέξτε Διαδικασία</option>
<option *ngFor="let diad of opts" [value]="diad.id"> diad.name </option>
</select>
</div>
<div> description </div>
You can find the working example from here Stackblitz
You can use ngModel and ngModelChange together to get the selected value
<select #proc [(ngModel)]="selectedObj" (ngModelChange)="showInfo()">
and inside showInfo method,
var selected = this.diadikasies.filter(x=> x.id == this.selectedObj.id);
Shouldn't it be
x.id === this.selectedObj.id in filter?– Augustin R
Aug 22 at 12:52
x.id === this.selectedObj.id
filter
yes thanks for correcting it
– Sajeetharan
Aug 22 at 12:53
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you so much. It was very simple, indeed, even though I hadn't thought about find().
– DimMalice
Aug 23 at 9:03