Here is a code snippet that showcases using actual json files instead of the "of" rxjs operator in Angular:
This section pertains to the Parent component.
import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
parentData = [];
selected = "";
ngOnInit(): void {
this.getParentJson().subscribe(
(data) => {
this.parentData = data;
}
)
}
getParentJson() {
return of([
{
id: 100,
name: 'Abc',
},
{
id: 101,
name: 'Xyz',
},
{
id: 102,
name: 'Efg',
},
]);
}
childCallback(ev){
console.log(ev); // Message received from the child component
}
}
This part covers the HTML for the Parent component.
<select [(ngModel)]="selected">
<option *ngFor="let p of parentData" [value]="p.id">
{{p.name}}
</option>
</select>
<app-child-select [idVal]="selected" (callback)="childCallback($event)"></app-child-select>
Now, let's look at the Child Component.
import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { of } from 'rxjs';
@Component({
selector: 'app-child-select',
templateUrl: './child-select.component.html',
styleUrls: ['./child-select.component.css']
})
export class ChildSelectComponent implements OnInit, OnChanges {
@Input() idVal:any = "";
@Output() callback = new EventEmitter();
data = [];
selected = "";
constructor() { }
ngOnInit() {
}
ngOnChanges(e){
console.log(e.idVal);
if(!e || !e.idVal || !e.idVal.currentValue){
this.data = [];
this.callback.emit({status: 'NO_ID_VALUE'});
return;
}
const v = e.idVal.currentValue;
this.loadData(v);
}
loadData(id){
this.getChildJson(id).subscribe(
(r) => {
this.data = r;
if(this.data.length === 0){
this.callback.emit({status: 'NO_DATA_FOUND'});
}
}
)
}
getChildJson(id) {
const arr = [
{
id: 100,
age: 10,
},
{
id: 100,
age: 20,
},
{
id: 101,
age: 25,
},
];
return of(arr.filter(e => e.id == id));
}
}
Lastly, here is the HTML content for the Child component.
<select [(ngModel)]="selected">
<option *ngFor="let p of data" [value]="p.id">
{{ p.age }}
</option>
</select>