A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data:

"Id":10001, "name":"John"

"Id":10002, "name":"Sam"

"Id":10003, "name":"Tom"

"Id":10004, "name":"Tom"

The child.json file should have this data:

"Id":10001, "age": 20

"Id":10002, "age": 50

"Id":10003, "age": 25

Retrieve the parent.json file using an HTTP GET request and display the names in a dropdown menu within the parent component.

When a name is selected from the dropdown, pass the corresponding ID to the child component. The child component will then fetch the child.json file through a similar HTTP call, match the ID, and display the age of the person.

If the ID is not found in the child.json file, the child component will send a message back to the parent component for display:

"No data present"

Remember to create a service along with the 2 components (parent and child).

Note: Do not share the nodemodule folder.

Answer №1

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing CORS problems when a web application imports JavaScript modules from different domains

Currently, I am in the process of developing a web application using NodeJS. The application is divided into a back-end responsible for handling database queries with MongoDB, and a front end built on a Node-based web server that utilizes interactjs alongs ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Retrieve a value from a nested JSON object and assign it to a new key in the same object with

I am facing a challenge with the following input JSON: { "stores": { "1100": { "metric1": "27", "metric2": "3013775", "indicator": 8.96 }, "1200" ...

Personalized Functions Using Material Design Expansion Panel Header Icon

Here's a unique material design accordion with an icon added to the panel header. I want to invoke my function 'myFun()' on click event, but currently, the expansion panel is toggling each time it's clicked (which is not the desired beh ...

Is the performance of `fillRect` hindered when painting on a 3D model?

Currently, I am in the process of developing a painting-type application using three.js/canvas. My goal is to enable users to paint directly onto a 3D model, updating the UV map accordingly. https://i.sstatic.net/DfMvB.png While I have achieved the desi ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

Decompressing Array in Vala/C

I need to input data using a text file that I'm piping in on my university's server. With two double values, a one-dimensional double array, and a two-dimensional double matrix, how can I import this into variables? Thank you so much for your h ...

Creating fresh records in LDAP server via an angular 4 application

I need to incorporate new users into my ldap system with OpenLDAP as the server. Is there a specific node module that I can utilize within my Angular application for this task? If anyone has an example demonstrating how to do this, it would be greatly ap ...

Accessing a .mov File Online for Everyone

Looking for a way to host my lengthy .mov file on my own server but display it in a YouTube-style player that is compatible with all browsers. Any suggestions on how to achieve this easily? ...

How to retrieve data from a JavaScript array in a separate JavaScript file

In my checklistRequest.js file, I populate an array and then try to access it in my Termine_1s.html file, which includes JavaScript code. Although I can access the array, when I attempt to iterate through it, only single digits are returned instead of stri ...

Firefox and IE are unable to make changes to cssRules

To update existing global CSS rules, I access the document.styleSheets property to locate the rule and make modifications. The selector can be modified by accessing the selectorText property. Sample CSS code: <style type="text/css"> .class { ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

How can I incorporate popups in React using mapbox-gl?

Currently utilizing mapbox-gl within React, everything seems to be functioning properly except for the integration of mapbox-gl's Popups. I have the function let Popup, but I am uncertain about how to incorporate it. renderMap() { if (this.props. ...

Creating a unique directive specifically designed to be used within an ng

I have a unique custom directive that I implemented in AngularJS. The directive is called within an ng-repeat loop, as shown below: The array of objects, selectedMealCalc.calculated_foods, is aliased as 'items' <!-- CUSTOM DIRECTIVE --&g ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

Adding values to a knockout data table without refreshing the page

I am currently experiencing difficulties with refreshing my knockout.js DataTable. I have a data table that loads correctly on page load using the attached function method. I also have multiple buttons (Display All, Allowed, Not Allowed) that display the t ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

Issue encountered with JSONWriter.setDateFormatter following the update of Struts framework from version 2.3.7 to 2.3.33: NoSuchMethodError

After upgrading from Struts version 2.3.7 to 2.3.33 using Maven, my web application which previously worked without any issues now encounters an exception when attempting to access a web page with an Ajax call to the server. The error message received is ...

Challenges that may arise when converting JSON to XML

What are the main challenges when mapping JSON to XML and vice versa? I have identified several issues that can arise, but it would be valuable to hear from others about their experiences in converting between the two formats. Here is my list of challenge ...