What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form.

How can I trigger validation for child forms from the parent component upon submission? I am using FormBuilder in each child component.

I am able to validate the child fields when the user interacts with them, but if they try to submit without entering any information or interacting with the fields, the validations are not displaying errors.

parent.component.html

<form>
    <child1></child1>
    <child2></child2>
    <child3></child4>
    <child4></child4>
''''
''''
''''
</form>

child1.component.html

<div formgroup="child1group">
      <div formarray= "child1array">
      ....
      ...
      ...
      </div>
</div

child2.component.html

<div formgroup="child2group">
      <div formarray= "child2array">
      ....
      ...
      ...
      </div>
</div

Can anyone guide me on how to implement this validation in Angular 4?

Answer №1

To pass the Formcontrol to the Parent component as OUTPUT, use the function SaveConsole() for validation when the button is clicked.

child1.component.ts

@Output() public childControls = new EventEmitter();

 public ngOnInit() {
        this.childControls.emit(this.child1group);   
        this.child1group.valueChanges.subscribe(() => {
            this.childControls.emit(this.child1group);
        });
  }

parent.component.html

   <form>
        <child1 (childControls)="child1Control = $event"></child1>
         <button (Click)=SaveConsole()> Submit </butto>
   </form>

parent.ts

   public child1Control: FormGroup;
   public SaveConsole() {
          if (this.child1Control.valid) {
            // SAVE FORM
          } else {
            this.validateAllFormFields(this.child1Control);  
          }
      }
     public validateAllFormFields(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateAllFormFields(control);
      }
    });
}

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 causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

Does Nativescript have a feature similar to "Hydration"?

It's been said that Phonegap offers an exciting feature called Hydration, which can lead to rapid and efficient deployments when combined with CD. Is it feasible to incorporate this concept into a Nativescript application? While I may not be well-ve ...

What is the process for initializing the default/prefilled value of an input element within a mat-form-field when the page loads?

I'm looking to create an HTML element where the default data (stored in the variable 'preselectedValue') is automatically filled into the input field when the component loads. The user should then be able to directly edit this search string. ...

Tips for removing red borders on required elements or disabling HTML validation

I am on a mission to completely eliminate HTML validation from my project. Although this question suggests that having all inputs inside forms can help, I am using angularjs and do not require a form unless I need to validate all fields in a set. Therefore ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Sharing data between components in Angular 4: How to pass variables and form content to

Perhaps my wording is incorrect. I am filling out a Client Form with the data from an API response within the NgOnInit function. ngOnInit() { this.indexForm = new FormGroup({ name: new FormControl(Validators.required), status: new FormCo ...

Encountering a module not found error when attempting to mock components in Jest unit tests using TypeScript within a Node.js

I'm currently in the process of incorporating Jest unit testing into my TypeScript-written Node.js application. However, I've hit a snag when it comes to mocking certain elements. The specific error I'm encountering can be seen below: https ...

Steps for generating a multer file using a link to an image

My current challenge involves downloading an image from a public URL, converting it into a multer file format, and then uploading it using an existing API. So far, I've experimented with axios using responseType: "blob" and responseType: "arraybuffer" ...

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Encountering an issue while trying to upgrade angular from version 8 to version 16. The error message states: "Unable to bind to 'something' as it is not recognized as a property of 'something'."

Currently in the process of upgrading an old Angular 8 project to Angular 16. The update has been completed, however, when compiling the project I am encountering multiple errors related to components not being able to bind to certain properties that are s ...

Extracting and transforming an array into a list with the desired outcome

Looking for a way to flatten the array below into a single line array using Typescript/JavaScript? Student: any = [ { "id": "1", "name": "Jhon", "Marks": { "Math": "90", "English": "80", "Science": "70" } }, { "id": "2", "name": "Peter", "Marks": { "M ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

MVC: Issue with client-side validation ceases to function after the initial opening and closing of SimpleModal AJAX popup

I am currently facing an issue with a view that includes a simplemodal popup window. When you click on a hyperlink, the window pops up, and if you try to submit the form in the popup without filling in any information, it displays the appropriate validatio ...