Passing data from the front-end of an Angular component (app.component.html) to the back-end of another component (other.component.ts)

Imagine a scenario involving basic crud operations. Within the app.component.html file, there are multiple input fields and buttons. Upon clicking a button in app.component.html, the value of an HTML field is sent to the 'other.component.ts' component. After processing (such as adding, subtracting, etc.), the result is displayed back in app.component.html.

Below is the content of app.component.html:

<a routerLink="posts/">Show Posts</a>
  <input type="number" [(ngModel)]="get-one-post-id">
  <a routerLink="/post-by-id">Show One Posts</a>

  <router-outlet>
  
  </router-outlet>
  

post-by-id-component.ts

import { Component, OnInit } from '@angular/core';
  import { DataService } from '../data.service';
  import { Observable } from 'rxjs';

  @Component({
    selector: 'app-post-by-id',
    templateUrl: './post-by-id.component.html',
    styleUrls: ['./post-by-id.component.css']
  })
  export class PostByIdComponent implements OnInit {

    posts: object;
    constructor(private dataService: DataService) { }

    ngOnInit(): void {
      // const id = ??
      this.GetPost(1);
    }

    async GetPost(id: number)
    {
      const response = await this.dataService.Get_A_Post(id);
      const dataService = await response.json();
      this.posts = dataService;
    }

  }
  

post-by-id-component.html

<div *ngFor="let post of posts">
    <h3>{{post.title}}</h3>
    <p>{{post.body}}</p>
  </div>
  

In the scenario, there is a need to extract the value from the field named get-one-post-id in app.component.html to post-by-id-component.ts [where // const id = ?? is commented]. However, a suitable method for importing this value has not been identified.

Answer №1

There are 4 different ways to exchange data between Angular Components:

  1. Parent to Child: Data Sharing through Input

  2. Child to Parent: Data Sharing through ViewChild

  3. Child to Parent: Data Sharing through Output() and EventEmitter
  4. Unrelated Components: Data Sharing with a Service

For more information on how these methods work, check out this informative article.

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

Why is the response from this HTTP request displaying array lengths instead of actual content?

I am currently working on a project involving fetching data asynchronously from an API. Everything seems to be working fine, except for when I attempt to add the correct answer to the incorrect answers array. Instead of displaying the content, only the len ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Update the data table after a new file has been uploaded

As a novice web developer, I embarked on my first project using Vue. In this project, I created a form for file uploads in Vue 2 and Laravel. If you want to take a look at the full code: View: https://pastebin.com/QFrBfF74 Data table user file: https:/ ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Steering Vue with Vuetify to output checked value

What's the correct method to pass the 'checked' value from a child component to its parent? I have a checkbox nested within a component that utilizes v-checkbox from Vuetify. I want to send the checked value to its parent component. Current ...

How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component: Input.html <form (submit)="getTransactions()"> <div class="form-group"> <label for="exampleInputEmail1"></label> <input type="t ...

Leverage Pinia store in Vue helper functions

I have been working on my Vue.js application and I am looking to implement some helper functions that will utilize a Pinia store within the app. These functions need to be accessible by multiple components. Should I define these helper functions directly ...

Incorporate the Angular library into my project privately without the need to publish

I have developed an Angular library called My-lib and I want to integrate it into my application named My-app without publishing it to the NPM repository. I attempted to use the npm link command after building My-lib with npm link /folder/My-lib/dist/My-l ...

React-table fails to show newly updated data

I am facing an issue with my react-table where real-time notifications received from an event-source are not being reflected in the table after data refresh. https://i.stack.imgur.com/q4vLL.png The first screenshot shows the initial data retrieval from th ...

Display a preview window once the image has been chosen

I have created an image preview div to show the selected image's thumbnail. Everything was working fine so far. But now, I want this div to be hidden when the page initially loads and only become visible when a user selects an image to upload. Here is ...

Display dynamic text from an input field in another div along with a checkbox

In the input field below, you can type something and then click the Add button. What will happen is that the text entered in the input field will be appended with a checkbox inside a div with the class .new-option-content. For a live example, check out th ...

Consistent integration into React component

I'm currently working on an application using the React library, but my current challenge lies within JavaScript ES6 itself. Within a component (page) that I've created, I have implemented a custom Floating Action Button (FAB): class Page exten ...

Ways to prevent a timeout when the score exceeds 1000

Could someone help me with clearing the interval and resetting the score in my code? It seems to be working fine, but when the score goes over 1000 and I hit reset, it doesn’t reset completely. I've tried placing the clearTimeout functions before e ...

To initiate the development environment, execute the following command: `cross-env NODE_ENV=

[email protected] start /Users/ssurisettii/Documents/il-17g5-app cross-env NODE_ENV=development npm run webpack-development sh: cross-env: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ER ...

Employing IF conditions within a form to refine options

I am looking to streamline the options in my form based on the car and transmission selected. I have set up the form, but I am struggling with the JavaScript code. I need help figuring out how to only display certain color options when Car 1 is chosen alon ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

Ways to exit the current browser window?

Is there a way to close the current browser window using JavaScript or another language that supports this functionality? I've tried using the window.close() function, but it seems to only work for windows opened with window.open(). Thank you in adv ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...