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





Thank you so much. It was very simple, indeed, even though I hadn't thought about find().
– DimMalice
Aug 23 at 9:03



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ