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

Sort the observable array by the property of its objects

Currently, I have an array of observables that I am iterating through using an *ngFor loop with the async pipe. I want to filter the observables based on a specific property value within the object. Starting array: [{ name: test1, type: type1}, { nam ...

Deleting an element from an array in Mongodb using Angular

My question remains unanswered: Delete an element from an array of an array in MongoDb In the process of creating a basic MEAN application similar to Stack Overflow, I have encountered an issue. Within my application, there are articles with upvotes and d ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

Tips for stopping the navigator from adding content to an HTML input in an Angular application

I am facing an issue with two input fields in my Angular project. These fields are supposed to take values automatically from the browser, and I have tried using the HTML autocomplete option without success. Here is a snippet of my HTML code: <div clas ...

How can I incorporate TypeScript paths into Storybook with Webpack version 5?

Storybook includes a pre-configured Webpack setup. Up until Webpack v4, it was possible to utilize tsconfig-paths-webpack-plugin and define custom tsconfig (or any other plugin) like so: const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plug ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser. There is a possibility that a user may not have any cars, resulting in a 404 error from the API. How can I handle this sc ...

What is the correct way to input the 'name' HTML attribute in an Ant Design select element?

I am facing an issue with the 'name' attribute in my Ant Design Select component. When trying to set the 'name' attribute, I encountered an error message that is causing issues. https://i.stack.imgur.com/Lzb4t.png Ant Design Select Co ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

The subsequent code still running even with the implementation of async/await

I'm currently facing an issue with a function that needs to resolve a promise before moving on to the next lines of code. Here is what I expect: START promise resolved line1 line2 line3 etc ... However, the problem I'm encountering is that all t ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Strict mode does not allow duplicate data properties in object literals within JavaScript

Challenge Description I am facing an issue with handling an optional variable called ByteRange. To accommodate this, I included 2 different URLs in the $resource. Upon doing so, I encountered the following error: Message: Error in parsing: "tools/tes ...

Hold on for the completion of the promise inside the external function

Currently, I am working on a project using Ionic2 + Laravel. My goal is to create an "interceptor" that will automatically add the JWT token for authentication from LocalStorage to all of my Http requests. To achieve this, I have created a Service with ...

Guide on resolving the error "Type 'Emits' does not have any call signatures" in Vue 3 with the combination of script setup and TypeScript

I've come across some code that seems to be functioning properly, but my IDE is flagging it with the following warnings: TS2349: This expression is not callable. Type 'Emits' has no call signatures Below is the code snippet in question: ...

Angular Binding issue - Unable to bind to 'ngModel' as it is not recognized as a valid property of 'input' element, despite the property being present

I have developed a component class like the one below and I am attempting to link the class fields to the template, but encountered the following error: ERROR in src/app/admin/projects/projects.component.html: 41:34 - error NG8002: Can't bind to &ap ...

Problem with rendering accordion list in Ionic 2

I am integrating an accordion feature into my Ionic2 application. Here is the code snippet from my component: export class ContactPage { public days : any[]; public shownGroup; constructor(public navCtrl: NavController) { this.days= ...

Improving type definitions in Typescript 2.6 using module augmentation leads to error TS2339: Property '' is not found on type ''

Currently utilizing the material-ui library version v1.0.0-beta. An update was released yesterday to v1.0.0-beta.28, however, the type definitions were not updated resulting in runtime errors while compilation remains successful. Encountering this error i ...

Displaying personalized message 'Loading...' while waiting for the data to be retrieved from the API

How can I display a 'Loading' text message until the data is fetched from the API? Currently, it just shows a message saying 'No data to display' I have searched through the documentation but couldn't find any related information. ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

In Typescript, a computed property name within a type literal must be associated with an expression that has a type of literal or a 'unique symbol' type.ts(1170)

I'm facing an issue with dynamically generating grid columns using the react-data-table-component library. Here is a sample code snippet showing how to statically define the columns: const columns = [ { name: 'Title', selector: (row: ...