What could be causing the malfunction in this dynamic input value form validation process?

Recently started working with Angular... I've created a reactive form (in the parent component) in Angular where the values are dynamically populated by a child component. Upon submitting this form, null values are saved because the form is not detecting the values even though they are visible in the input fields.

Note: The input values are displayed in the parent component (communication from child to parent is successful)

Below is the necessary code snippet:

Child Component TypeScript file

@Output() messageToEmit = new EventEmitter<string>();
@Output() messageToEmit1 = new EventEmitter<string>();
@Output() messageToEmit2 = new EventEmitter<string>();
@Output() messageToEmit3 = new EventEmitter<string>();

save(selectedItem: any, index: number)
{
var num1 = selectedItem.f;
var num2 = selectedItem.l;
var num3 = selectedItem.e;
var num4 = selectedItem.p;

this.messageToEmit.emit(num1);
this.messageToEmit1.emit(num2);
this.messageToEmit2.emit(num3);
this.messageToEmit3.emit(num4);
 }

Child Component HTML file

<table class="w3-table-all">
<thead>
  <tr class="w3-red">
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email</th>
    <th>Password</th>
     <th>Edit / Update</th>
  </tr>
 </thead>
<tr *ngFor="let thing of things; let i = index;">   
  <td><input type="text" value="{{thing.f}}" id="{{ 'f' + i }}"> </td>
  <td><input type="time" value="{{thing.l}}"  id="{{ 'l' + i }}"> </td>
  <td><input type="email" value="{{thing.e}}"  id="{{ 'u' + i }}"> </td>
  <td><input type="password" value="{{thing.p}}"  id="{{ 'p' + i }}"> </td>
  <td >
    <button (click) = "save(thing,i)">Edit</button>
    </td>
  </tr> 
  </table>

Parent Component TypeScript file

export class ParentComponent implements OnInit {
edited_values: string;
edited_values1: string;
edited_values2: string;
edited_values3: string;
edited_values4:  number;

name = 'Registration';
signupForm:FormGroup;
FirstName:string = "";
LastName:string = "";
Email:string = "";
Password:string = "";

constructor(
private frmbuilder: FormBuilder,
)
{
this.signupForm= frmbuilder.group({
fname:new FormControl('', [
Validators.required,
Validators.maxLength(50),
Validators.minLength(3),
Validators.pattern('^[a-zA-Z ]*$')
]),
lname:new FormControl('', [
Validators.required,
Validators.maxLength(50),
Validators.minLength(3),
Validators.pattern('^[a-zA-Z ]*$')
]),
 email:['',[Validators.required,Validators.email]],
userpassword:new FormControl('', [
Validators.required,
Validators.maxLength(50)
])
});
} 
ngOnInit(){
}

postdata(signupForm:any)
{
this.FirstName=signupForm.controls.fname.value;
this.LastName=signupForm.controls.lname.value;
this.Email=signupForm.controls.email.value;
this.Password=signupForm.controls.userpassword.value;

this.signupForm.reset();
}

getMessage(message: string) {
this.edited_values = message;
}
getMessage1(message1: string) {
this.edited_values1 = message1;
}
getMessage2(message2: string) {
this.edited_values2 = message2;
}
getMessage3(message3: string) {
this.edited_values3 = message3;
 }
reset(){
this.signupForm.reset();
}
}

Parent Component HTML file

<form id="contact" [formGroup]='signupForm' (ngSubmit)="postdata(signupForm)">
<h3> Register Now! </h3>  
<div class = "form-group">
  <input type="text" formControlName='fname' placeholder="Your First name" value={{edited_values}}>
</div>
<div *ngIf="signupForm.controls.fname.invalid && signupForm.controls.fname.touched">
<small> Please enter a valid first name (only letters)!  </small>
</div>
<br>
<div class = "form-group"> 
<input type="text" formControlName='lname' placeholder="Your Last name"
value={{edited_values1}}>
</div>
<div *ngIf="signupForm.controls.lname.invalid && signupForm.controls.lname.touched">
<small> Please enter a valid last name (only letters)!  </small>
</div>
<br>
<div class = "form-group">
<input type="text" formControlName='email' placeholder="Your Email address"
value={{edited_values2}}>
</div>
<div *ngIf="signupForm.controls.email.invalid && signupForm.controls.email.touched">
<small> Invalid email address entered!  </small>
</div>
<br>
<div class = "form-group">
<input type="password" formControlName='userpassword' placeholder="Your password"
value={{edited_values3}}>
</div>
<div *ngIf="signupForm.controls.userpassword.invalid && signupForm.controls.userpassword.touched">
<small> Password requirements: minimum 8 characters, at least 1 uppercase letter, 1 lowercase letter, 
1 number, and 1 special character. </small>
</div>
  <br>
    <div>      
   <button type="submit" > Submit </button>
   <button type="reset" (click) = "reset()"> Reset </button>
 </div>
 </form>
 </div>
 <app-edit 
 (messageToEmit)="getMessage($event)"
 (messageToEmit1)="getMessage1($event)"
 (messageToEmit2)="getMessage2($event)"
 (messageToEmit3)="getMessage3($event)"
 ></app-edit>

Answer №1

Hey @ASHISH, remember that when working with ReactiveForms, you should avoid using [value] in the inputs and only use formControlName.

<!---AVOID--->
<input type="text" formControlName='fname' placeholder="Enter your First Name" value={{updated_values}}>

<!--CORRECT-->
<input type="text" formControlName='fname' placeholder="Enter your First Name">

Also, make sure to change the input value using the "setValue" method explained here. Your getMessage function should look like this:

getMessage(message: string) {
   this.signupForm.get('fname').setValue(message)
}

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

Setting the name of the router-outlet dynamically

How can I dynamically set the name of a router-outlet in Angular 2? I am trying to create a generic component that includes a router-outlet. Example Template : <nav class="nav menu"> <a *ngFor="let navRoute of navigationRoutes" class="nav-l ...

Guide to exporting dynamic variables in TypeScript

I've been working on transitioning some Node JavaScript code to TypeScript. One of the files I'm dealing with is called keys.js let keys; try { // eslint-disable-next-line security/detect-non-literal-fs-filename keys = JSON.parse(fs.readFile ...

Implement a grid control in Kendo-UI for Angular 2 that includes checkboxes in the first column

What is the process for adding a checkbox to the first column of a Kendo UI Angular2 grid? How can the checked status be retrieved for each row in the data? ...

Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output ...

What is the best way to define a general class within the constructor of another class in TypeScript?

Is there a way to inject a subclass into a class during its constructor using TypeScript? I've tried to demonstrate my idea with some pseudo-code here: type GenericConstructor<T> = { new (): T; } class MyClass { constructor( SubClass: G ...

Oops! The program encountered an issue where it couldn't access the "Point" property because it was undefined. This occurred while working with openlayers 3 and jsts on

I am currently working on implementing a buffer function for some features that have been drawn on a map following this particular example. However, I am encountering the following error: ERROR TypeError: Cannot read property 'Point' of undefin ...

Is there a way to use openapi-generator with typescript-angular to generate just a module within an existing Angular project instead of creating a separate package?

Currently, I am utilizing the openapi-generator tool specifically for typescript-angular. Although I have been able to successfully generate an Angular module along with all its components, it results in a separate npm package. While I acknowledge the ad ...

Ways to broaden the type signature of a Typescript comparator in order to facilitate sorting by properties nested within objects?

Here is a function that I created: arr.sort(alphabeticallyBy("name")) The function has the following signature: <T extends string>(prop: T) => (a: Partial<Record<T, string>>, b: Partial<Record<T, string>>) => ...

Instructions on customizing node options for the angular/cli ng command

After recently updating to node.js v14, I encountered some warnings while building an Angular 9 package. ng build –prod myPackage (node:14432) Warning: Accessing non-existent property 'lineno' of module exports inside circular dependency (Use ...

Which objects can be looped through in Aurelia templating?

In the documentation for Aurelia, it mentions that repeaters can be used with arrays and other iterable data types, including objects, as well as new ES6 standards like Map and Set. Map is usually recommended, as shown in the example below: <template&g ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Iterating over elements with a custom width using ngFor in Bootstrap

I'm currently using *ngFor to cycle through multiple images as the background of each column in a row using Bootstrap. One thing I'm wondering is how to control the width of each column. For example, if I have 10 images, how can I adjust the widt ...

Guide on properly defining typed props in Next.js using TypeScript

Just diving into my first typescript project and finding myself in need of some basic assistance... My code seems to be running smoothly using npm run dev, but I encountered an error when trying to use npm run build. Error: Binding element 'allImageD ...

Awaiting the completion of Promises within a for-loop (Typescript)

I'm struggling with a for-loop and promises in my angular2 project. I have multiple methods that return promises, and after these promises are resolved, I want to populate an array in the class using Promise.all(variable).then(function(result){....... ...

Looping through a static array of objects using *ngFor results in continuous DOM updates

My issue involves a basic component that iterates over a static array of objects, displaying the content. Once this component is integrated into the larger application, the content appears correctly, but I am unable to register any click events on it. Upon ...

Unable to verify the authenticity of every file I choose to upload

Currently, I am in the process of learning how to develop a mean stack app, specifically focusing on creating an ecommerce type application. The main issue that I have encountered revolves around image uploading. My goal is to upload multiple files simult ...

Ways to print several tabs at once in Angular 4

In my Angular 4 application, I have implemented a feature with 4 tabs ('tab1', 'tab2', 'tab3', 'tab4') on the screen. Each tab corresponds to an Angular component that is dynamically loaded. When a user lands on the ...

Guide on displaying and handling server-side validation errors within an angular form

I recently started working with Angular and encountered a problem I can't seem to solve. In my form, I need to display server validation errors from a Laravel REST API response. Although I can see the error message in the console, I'm unsure how ...

Sending information from a parent component to a child component within an Angular application

How can I efficiently pass the this.formattedBookingPrice and this.formattedCheckingPrice values to a child component using the value array instead of static values, especially when they are inside the subscribe method? This is my parent component. expor ...

Utilizing generic functions as arguments in other functions

Imagine if I were to create a type called CoolType in this manner: type CoolType<T> = {message: string, result: T} Next, let's define a type called CoolFunction which represents a function that returns CoolType: type CoolFunction = <T>( ...