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

Calculate the date input in Angular 7 by subtracting calendar days

As a user of this Angular 7 application, you are required to choose a date from a calendar input and then determine what day it was 40 days ago. Unfortunately, I have not been able to accomplish this in Typescript yet. There are numerous JavaScript solutio ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

Utilizing a search feature to navigate through JSON data in a Ruby on Rails

I'm currently integrating JSON data into my Rails application. I am aiming to implement a search functionality that can look up the name column in the JSON data. Are there any gems or resources available that could assist me in accomplishing this? da ...

Is there a way to attach a React component to an HTML element called i?

I've been implementing the winbox modal library and have encountered an issue when trying to add a React node to it. The modal offers an html parameter that accepts an HTML string like div.innerHTML = <div>hello</div>. The code snippet is ...

Pass an array of strings via an HTTP request to PHP and retrieve it using the $_GET superglobal

I need to send a collection of values stored in a String[] through an HTTP request and then access these values in PHP using the $_GET method. The number of values contained in the String[] is not fixed. I have attempted the following: List<Nam ...

Implementing dual pagination components in Vue JS for dynamic updates on click

Having two pagination components on a single page is convenient for users to navigate without scrolling too much. One component is placed at the top and the other at the bottom. The issue arises when I switch to page 2 using the top component, as the bott ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

Experiencing a result of NaN following a mathematical operation on variables

While working with an array obtained from a JSON response, I am encountering NaN after performing addition operations. var a = new Array(); var b = 0; var c = 0; alert(b); for (var x = 0; x < length; x++) { a[x] = response.data[x] } for (var i = 0; ...

What is the procedure for attaching console.log to "l" in vue.js?

The code in main.js includes the following: window.l = function () { } try { window.l = console.log.bind(console) } catch (e) { } It functions properly in non-Vue applications. However, when trying to use it in a Vue action/method like this: l("test") ...

Error encountered while parsing JSON file: Segmentation fault

I'm looking to extract information from a JSON file that looks something like the one below: {"first":10, "second":"0", "P1":"1.e-20","P2":"1000","P3":"1000","P4":"1000","P5":"1"} Having limited experience in this area, I decided to experiment with ...

Strange behavior observed in Angular Reactive form

I've been troubleshooting this code snippet: login.component.html <div class="main"> <div class="image"> <img src="./assets/icons/login.png" alt="Login"> <p>Sign in t ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Is it possible to display one division on top of another with a transparent opacity effect in HTML?

I'm struggling with designing web pages and currently working on a page on codepen.io using code from this link. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...

Angular with NX has encountered a project extension that has an invalid name

I am currently using Angular in conjunction with nx. Whenever I attempt to execute the command nx serve todos, I encounter the following error: Project extension with invalid name found The project I am working on is named: todos. To create the todos app ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

An issue encountered with getServerSideProps in NextJS 12 is causing a HttpError stating that cookies are not iterable, leading

Currently, I have an application running smoothly on my localhost. However, when it comes to production, an unexpected error has popped up: Error: HttpError: cookies is not iterable at handleError (/usr/src/.next/server/chunks/6830.js:163:11) at sendReques ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel Input: import React, { useState } from "react"; import styled ...

The error message 'Cannot read property 'navigate' of undefined' is displayed because the function '_this.props.navigation.navigate' is not

I'm facing an issue trying to access 'Home' from Form.js. Despite my efforts in arrowF, routes, and other methods, the same error persists. How can I resolve this? In my Form.js file, when I call onPress=(), I have tried using functions, ...