Transmit information between components through a form

Is there a way to transfer data from one component to another in Angular? I have two components set up and I am currently using a selector to display the HTML content in the first component. Now, I need to figure out how to send the data entered in a form to the first component.

Product Component HTML File

<form id="form" #form="ngForm" (ngSubmit)="onSubmit(form)">
  <label>
    <div class="field-heading">Name</div>
    <input type="text" [(ngModel)]="product.name" name="productName" class="theme-input" id="text" placeholder="Enter product name">
  </label>
  <product-variant></product-variant>
</form>

Product Component TypeScript File

export class ProductComponent implements OnInit {
 variant = new Variant();
 product= new Product();
 constructor() { }
 ngOnInit() {

 }
 onSubmit(){
   console.log(this.product);
   console.log(this.variant);
}

ProductVariant Component HTML File

<label>
  <div class="field-heading">Starting Inventory</div>
  <input type="text"  [(ngModel)]="variant.reorderLevel" name="reorder" class="theme-input" id="text" placeholder="Starting Inventory">
</label>

ProductVariant Component TypeScript File

import { Component, OnInit } from '@angular/core';
@Component({
  templateUrl: 'product-variant.component.html',
  selector: 'product-variant'  
 })
export class ProductVariant implements OnInit {
  variant = new Variant();
  // Need to find a way to pass data from this component to the product component
}

Answer №1

Give this a shot:

Live Demo

Main Product Component HTML

(onVariantChange)="variant = $event"

<form id="form" #form="ngForm" (ngSubmit)="onSubmit(form)">
    <label>
<div class="field-heading">Name</div>
<input type="text" [(ngModel)]="product.name" name="productName" class=" theme-input" id="text" 
placeholder="Enter product name">
</label>
    <product-variant (onVariantChange)="variant = $event"> </product-variant>
</form>


-----------------------------------------
product : {{product | json}}
variant : {{variant | json}}

Product Variant Component HTML

(ngModelChange)="onChange()

<label>
  <div class="field-heading">Starting Inventory</div>
  <input type="text"  [(ngModel)]="variant.reorderLevel" name="reorder" class=" theme-input" id="text" 
placeholder=" Starting Inventory" (ngModelChange)="onChange()">
</label>

Product Variant Component TypeScript

onChange() {
      this.onVariantChange.emit(this.variant)
    }

  @Output() onVariantChange = new EventEmitter();



  onChange() {
    this.onVariantChange.emit(this.variant)
  }

Answer №2

You Have the Power to Modify Code Accordingly

product component.html

<form id="form" #form="ngForm" (ngSubmit)="onSubmit(form)">
 <label>
 <div class="field-heading">Name</div>
<input type="text" [(ngModel)]="product.name" name="productName" class=" theme-input" id="text" 
placeholder="Enter product name">
</label>
<product-variant (variant)=getVariantvalue($event)> </product-variant>
</form>

product component.ts

export class ProductComponent implements OnInit{
 variant = new Variant();
 product= new Product();
 constructor() { }
 ngOnInit() {

 }
onSubmit(){
   console.log(this.product);
   console.log(this.variant);
}
getVariantvalue($event){
  this.variant = $event
}
}

ProductVariant component.ts

import {Component, OnInit, ViewChild, EventEmitter, Output} from '@angular/core';

@Component({
  templateUrl: 'product-variant.component.html',
  selector: 'product-variant'
})
export class ProductVariant implements OnInit {
  @Output()
  returnVariant: EventEmitter<Variant> = new EventEmitter();
  variant = new Variant();

// send data from this component to the product
  returnVariant() {
    returnVariant.emit(variant)
  }
}

Explore Angular Guid component-interaction

Hopefully, this information proves useful..!

Update: For a more in-depth explanation, consider visiting:

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

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Expanding unfamiliar categories

Currently, I am working with Gutenberg blocks in a headless manner. Each Gutenberg block is defined by the following structure: type Block = { name: string; className?: string; key?: string | number; clientId: string; innerBlocks: Block ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...

Database records failing to update after deployment

After deploying my next js site using Vercel, I encountered an issue with the functionality related to adding, getting, editing, and deleting data from MongoDB. Although all functions were working perfectly locally, once deployed, I noticed that while I co ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

After transitioning to TypeScript, the CRA app is encountering issues loading CSS files compiled by SASS

My React application was originally created using create-react-app and I had been successfully loading scss files with the node-sass package. However, after deciding to switch to TypeScript following the steps outlined in , my css files are no longer being ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Having trouble iterating over an array in Angular's TypeScript

I've been attempting to loop through an array of objects in TypeScript, but encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined TypeError: Cannot read property 'fo ...

ngModel not refreshed in ng-pick select directive

Within my code, I am utilizing the ng-select component which is initially set up in the following HTML format. <ng-select id="SelectType" placeholder="Student" [multiple]="true" [items]="students" groupBy="type" [selectableGroup]="false" ...

Leverage Angular to implement Bootstrap 5 tooltip on elements created dynamically

Our Angular-14 application uses Bootstrap-5 and I am currently attempting to add a tooltip to an element that is dynamically created after the page loads. The new element is based on an existing element, shown below: <span [ngbTooltip]="tipSEConte ...

There are no HTTP methods being exported in this specific file. Remember to export a named export for each individual HTTP method

Currently, I am working on a React.js/Next.js project that incorporates Google reCAPTCHA. The frontend appears to be functioning properly as I have implemented print statements throughout the code. However, I am encountering an error in the backend display ...

Issue with running Angular Application through docker-compose.yml file is stopping the execution

Below is the docker file I have created for my angular application: Dockerfile: # base image FROM node:10.16.0-alpine AS build-step # set working directory WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:1.16.1-alp ...

Display corresponding JSON images of items within an *ngFor loop in Angular

For my latest project, I am using Angular for the front-end and Laravel for the back-end. The issue I'm facing is with displaying images in Angular that are stored in Laravel storage. The image URLs are stored in the database in JSON format like this: ...

Running NG BUILD from Gulp can be done using either child-process.spawn or by disabling all output in child-process.exec

Have you come across a similar question like this Call "ng build" from inside a gulp task? I have found a way to successfully build Angular using Gulp in order to prevent overflowing the output buffer. Here's how I achieved it: const child ...

Utilizing TypeScript to Populate an observableArray in KnockoutJS

Is there a way to populate an observableArray in KnockoutJS using TypeScript? My ViewModel is defined as a class. In the absence of TypeScript, I would typically load the data using $.getJSON(); and then map it accordingly. function ViewModel() { var ...

How can I make sure that the combobox in my Ionic app is aligned with the text fields in a row?

From the image provided, it's evident that my HTML code looks like this: <ion-row> <ion-col> <ion-item> <searchable-ion-select isModal="true" name="country" valueField="code" [(ngModel)]="country" title="Country" ...

Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code: export const enum ComplianceType { ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT', CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE', ARCHITECTURE_ASSIGN ...