How can data be transferred from child component inputs to a parent form in Angular's template-driven approach?

It seems like this should be a straightforward task, but I'm encountering conflicting instructions on how to achieve it. I have three child components, each with their own set of input controls that are supposed to feed into a parent component. However, the parent component is not receiving the input from the child components. The code snippet below is what I currently have; it may be incomplete, as I've been trying different methods to make this work. Any help would be greatly appreciated!

Child template #1 (partial):

<input type="text"
        pInputText
        name="name" id="name"
        ngModel #name="ngModel"
        required [minlength]="5" [maxlength]="40"
        placeholder="First LastName"
        (change)="onNameEntered($event)">

Child component:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { DropdownOptions } from 'src/assets/dropdownOptions';
import { ApplicantInformation } from 'src/app/_models/applicantInformation.model';


@Component({
  selector: 'app-applicant-information',
  templateUrl: './applicant-information.component.html',
  styleUrls: ['./applicant-information.component.css']
})
export class ApplicantInformationComponent implements OnInit {
  name: string = '';
  phone = '';
  address = '';
  city = '';
  state = '';
  zipCode = '';

  options: any = new DropdownOptions;
  sts: string[] = [];

  @Input() ngModel: any = new ApplicantInformation(this.name,this.phone,this.address,this.city,this.state,this.zipCode)
  @Output() nameEntered = new EventEmitter<{ $event: any }>();
  
  onNameEntered($event: any) {
    this.nameEntered.emit({$event});
  }

  constructor() {
    this.sts = this.options.strAbbrs;
  }
  ngOnInit(): void {


  }
}

Parent template (partial):

<form #onePlusThreeColumnForm="ngForm">
  ...
  <app-applicant-information
              (nameEvent)="receiveName($event)"></app-applicant-information>
  ...

<button
  type="submit"
  class="p-button p-component"
  [disabled]="!onePlusThreeColumnForm.valid"
  (click)="login(onePlusThreeColumnForm)">
  Submit
</button>
</form>

Parent component:

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

import { ApplicantInformation } from 'src/app/_models/applicantInformation.model';
import { BiometricInformation } from 'src/app/_models/biometricInformation.model';

import { ThreeColumn } from '../../_models/threeColumn.model';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-one-plus-three-column-form',
  templateUrl: './one-plus-three-column-form.component.html',
  styleUrls: ['./one-plus-three-column-form.component.css']
})
export class OnePlusThreeColumnFormComponent implements OnInit {

  firstColumnInformation: any = new ApplicantInformation('','','','','','');
  secondColumnInformation: any = new BiometricInformation('','',0,0,0,'');
  thirdColumnInformation: any = new ApplicantInformation('','','','','','');

  constructor() {
  }

  model = new ThreeColumn(
    this.firstColumnInformation,
    this.secondColumnInformation,
    this.thirdColumnInformation
  );

  ngOnInit(): void {
  }

  name: string = '';

  receiveName($event: any) {
    this.name = $event;
  }

  login(thisForm: NgForm) {
    console.log(this.model);
    console.log(JSON.stringify(thisForm.value));
  }
}

Console output: https://i.sstatic.net/RawcB.png

Answer №1

(eventHandler)="handleEvent($event)"

Make sure to use a descriptive name for your EventEmitter, such as

(userInput)="handleInput($event)"

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

When transmitting JSON data from the View to the Controller in ASP.NET MVC, the received values are

I'm facing an issue with sending JSON data from an MVC View to Controller. All I seem to get in the Controller is: https://i.sstatic.net/4pKNF.png The JSON I send in Url.Action looks like this: (I create it myself by adding arrays together using .pu ...

The @RequestParam annotation seems to be failing to retrieve a value

When a user inputs their phone number in my application, I want to check if that phone number is already in the database. To do this, I am using an onchange event to instantly send the phone number for validation. However, I am facing an issue where the da ...

Checking the submission text field with Javascript is being confirmed

It seems I've made a small mistake somewhere, and I would appreciate it if someone could help me find it. I'm attempting to validate a postcode in a form field once it's been entered. I've tried similar code in PHP, and it works fine, b ...

Angular: Issue with setting a new value in child component on the second attempt via @Input directive

Implementing a child component to manage a dropdown feature. The parent component includes a reset button to revert the user's selection in the dropdown (child component) back to 'None'. Check out the code link here. app.component.html: ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Troubleshooting in Angular 7: When Auth0 parseHash response is returning null

Having trouble with Auth0. Upon sign-out and browser refresh, my application is unexpectedly triggering the login event again and encountering user profile issues. The root of the problem seems to lie in the parseHash method within the authentication serv ...

Declaring a function in TypeScript triggers an error notification

I encountered a typescript error while running my code stating that "require" is not a function. To resolve this, I declared the function beforehand; however, a new typescript error now occurs saying "Modifiers cannot appear here." Can anyone assist me w ...

What is the process for utilizing JavaScript to parse a JSON file stored locally?

I am trying to retrieve data from a JSON file located locally using JS/jQuery. Despite finding numerous similar questions on Stack Overflow, I have not found the right solution. All answers seem to give me a jquery.min.js:4 XMLHttpRequest cannot load file ...

Creating a ripple effect on a circle with CSS and HTML when it is clicked

Can anyone assist me in creating a wave effect around the circle when it is clicked? To better visualize what I am trying to achieve, you can view this GIF image. Appreciate your help in advance! ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

"Utilizing the jQuery ID selector along with the validation capabilities of

Recently, I stumbled upon some code I wrote a few days back, and surprisingly, it's working flawlessly, although I can't quite figure out how. I'm reaching out to see if anyone could shed some light on this for me. Within my validation code ...

Unable to locate request object during post request

I've created a pug form with the following structure: extends layout block content h1 David A Hines h2 #{posts[0].title} p #{posts[0].body} div form(action='/insert_post',method='post') div(id='title_div' ...

Is it possible to make a distinctive choice from the dropdown menu?

I need help with my html page that has 10 dropdowns, each with options 1 to 10. How can I assign options uniquely to each dropdown? For example, if I select option 1 in dropdown 1, that option should be removed from the other dropdowns. If I deselect an ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

Length of Angular events

I am embarking on the journey of building an Angular web application and I find myself in need of tracking various performance time-related data: The duration between clicking a button and the API call being initiated The duration between the API call be ...

Avoiding an endless JavaScript loop in Selenium/PhantomJS to improve test automation sanity

Imagine a scenario where a web application contains JavaScript code like the one below: for(i=0; i > -1; i++){var a=1}; // Infinite loop If I attempt to navigate this web app using Selenium or PhantomJS, it will become unresponsive indefinitely. Is t ...

What are the best ways to establish communication among JavaScript modules?

I have multiple modules in my application, each with their own responsibilities, but I'm unclear on how they should communicate with one another. What is the best way for modules to interact with each other? How can modules notify or listen to e ...

Develop a diverse range of form types within Django forms

Even though I know how to create a form set based on a given form type, it doesn't completely resolve the issue at hand. Imagine having a fast food portal where users can add items and depending on their selection, additional fields need to be dynami ...

Tips for creating a click event for a ViewChild element reference in Angular 8

Having trouble getting the click event to work for an element reference in typescript. Can anyone provide guidance on how to properly write a click event for an element reference? app.component.ts: @ViewChild('testElem') el:ElementRef; @Vie ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...