Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search product component and mine focusing on credit cards.

Purpose and Goal

Upon selecting a credit card from the dropdown box in the search box, my credit card component will be displayed(and validated as numbers are entered).

I aim to link the data from my credit card component (as the child) to the model of the defined SearchProductModel that he created. I came across a similar issue on this post (Pass data from child to parent component Angular2) which resonates with my situation.

Here are details of the components and templates:

creditcard.component.ts

@Component({
selector:'creditcard',
templateUrl:'./app/creditcard/creditcard.component.html' 
})

export class CreditcardComponent {
creditForm: FormGroup 

ccnumber = new FormControl('', [Validators.required, validateCreditcard]);

constructor(fb:FormBuilder){
this.creditForm = fb.group({"ccnumber":this.ccnumber})
}

search-product.component.ts

    @Component({
    selector:'search-product',
    templateUrl:'./app/search/search-product.component.html' 
    })

    export class SearchProductComponent{
products: Product[]
model = new SearchProductModel();
searchResult:string;

constructor(private searchProductService: SearchProductService){}

ngOnInit(): void {
this.searchProductService.getProducts().subscribe(products => this.products = products, error => console.log(error));
}

onSubmit(): void {
this.searchProductService.searchProduct(this.model).subscribe(result => this.searchResult = result, 
error => console.log(error));;
}

search-product.component.html

<form (ngSubmit)="onSubmit()" #searchForm="ngForm" autocomplete="off">
<p>
<md-select placeholder="Product (optional)" [(ngModel)]="model.productId" name="product-id" id="product" style="width:250px">
 <md-option *ngFor="let product of products" [value]="product.Id">{{product.Name}}</md-option>
</md-select>
</p>

<div [ngSwitch]="model.productId">
 <p *ngSwitchCase="1">
<creditcard></creditcard>
</p>
<p *ngSwitchDefault>
<md-input-container style="width: 250px">
<input mdInput [(ngModel)]="model.productNumber" name="product-number" id="product-number" required/>
<md-error>product number required</md-error>
</md-input-container>

<button md-button type="submit" id="btn-search">Search</button>
</form>

creditcard.component.html

<form [formGroup]="creditcardForm">
<div class="form-group">
<md-input-container>
 <input mdInput formControlname="creditcardnumber" id="creditcardnumber" name="creditcardnumber"/>
<div *ngIf="creditForm.get('creditcardnumber').dirty && creditcardForm.get('creditcardnumber').hasError('validCreditcard')">Not correct credit card</div>
</md-input-container>
</div>
</form>

It's evident that mixing template-driven and reactive approaches is not recommended, so refactoring is in order down the line. However, for now, I'm puzzled about how to integrate my credit card input with his model.productId. I acknowledge that I'm still learning the ropes here and struggling to grasp it all.

Any assistance would be greatly appreciated.

Answer №1

After realizing a mistake I made, I thought my solution was unsuccessful at first. Fortunately, by carefully following the explanation provided in the link above, I was able to make it work. I included the Emitter in my component and set up the other component to listen for events from mine. This simple adjustment proved to be the key to success.

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

What is the method for retrieving the index of an enum member in Typescript, rather than the member name?

Here is an example of how to work with enums in TypeScript: export enum Category { Action = 1, Option = 2, RealEstateFund = 3, FuturesContract = 4, ETFs = 5, BDRs = 6 } The following function can be used to retrieve the enum indexe ...

Tips for integrating Pico CSS into the overall scss stylesheet of your Angular project

After setting up a fresh Angular 17 project using SCSS for the stylesheet format, I decided to integrate Pico CSS into my development. However, implementing it according to the instructions in the Pico CSS documentation led to an error: ✘ [ERROR] Can&apo ...

Analysis of cumulative revenue using Palantir Foundry Function

I am in need of creating a function that can transform raw data into target data. The raw data consists of a table with columns for customer, product, and revenue, while the target data includes customer, revenue, and cumulative revenue. customer produ ...

Managing Angular routing: selectively updating named outlets without reloading submodules

My routing configuration currently reloads Module2 ListComponent on every routing event. However, I want to prevent the list from reloading when a user clicks on a list item within ListComponent. Specifically, when navigating from module2/route1 to module ...

The error message "Type 'null' cannot be assigned to type 'Element | DocumentFragment'" occurs when using Nextjs/React createPortal

I am completely new to typescript. Currently, I'm working on a project that has a lot of pre-configured react components in JavaScript files (.js). My task now is to convert everything to TypeScript (.tsx) without triggering any ESLint errors. Unfort ...

Unable to pass a parameter through an Angular http.get request

I've encountered an issue where I am attempting to pass the page number and page size values to a web API, but for some reason, no parameters are being passed. I have thoroughly debugged the application in VS Code, and verified that the pagingModel ob ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

Guide on accessing an element from a predicate object in Typescript while using Angular

I'm trying to wrap my head around how to access an element that exists on an object of a specific type but is defined as a type predicate. For example, let's say we have a Team defined as: let team$: Observable<ErrorModel | Team> The res ...

I am struggling to comprehend the concept of dependency injection. Is there anyone available to provide a clear explanation for me?

I am working on a NestJS application and trying to integrate a task scheduler. One of the tasks involves updating data in the database using a UserService as shown below: import { Injectable, Inject, UnprocessableEntityException, HttpStatus, } fro ...

Angular 2 tool for transforming Excel files into JSON format

I am looking for a way to read and convert XLSX files into JSON using Angular 2. Here is the code I am currently using: readFile(){</p> <pre><code>var testUrl= "../assets/US175939.xlsx"; var oReq = new XMLHttpRequest(); oReq.open("GET", ...

nested components in AngularJS

I am facing an issue with my two components in HTML where the inner component is not populating using the template specified in its templateUrl property. //first component angular.module('app').component('toolCtrl', { templateUrl: ...

Ways to integrate user input into the header of an Angular HTTP post method

I need help figuring out how to incorporate user input into the header of a post method I am working with. I understand that some kind of binding is necessary, but I'm struggling to implement it in this case. Currently, I have a variable called postDa ...

Creating a custom class to extend the Express.Session interface in TypeScript

I'm currently tackling a Typescript project that involves using npm packages. I am aiming to enhance the Express.Session interface with a new property. Here is an example Class: class Person { name: string; email: string; password: strin ...

What could be the reason for the component not receiving data from the service?

After attempting to send data from one component to another using a service, I followed the guidance provided in this answer. Unfortunately, the data is not being received by the receiver component. I also explored the solution suggested in this question. ...

Troubleshooting Angular Karma Testing: Uncaught ReferenceError - Stripe not recognized

When running tests with karma, I encountered the following error: ReferenceError: Stripe is not defined Component import { Component, OnInit } from "@angular/core"; import { FormBuilder } from "@angular/forms"; import { Router } from & ...

Using AngularJS to access form field ids that are generated dynamically

I am dynamically generating form fields using ng-repeat and everything is functioning correctly. However, I now want to incorporate an angular datepicker component that is based on a directive. The issue I am facing is that it only seems to work with stat ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Is it possible to have multiple Mat-Dialogs simultaneously displayed on screen?

Is it possible to show a mat dialog on top of another mat-dialog component? I have a grid with an edit button, and when the user clicks on it, an Edit Dialog window opens for editing data. If the user wants to close this window without saving, I want to di ...

Can @Input() be declared as private or readonly without any issues?

Imagine you're working in an Angular component and receiving a parameter from its parent. export class SomethingComponent implements OnChanges { @Input() delay: number; } Would it be considered good practice, acceptable, or beneficial to designat ...