Validation in Angular 2+ for child components

I am seeking assistance with Angular as I do not have expert knowledge in it. My goal is to implement form validation in a component named "viewForm". This form is created using an object array loop called "points". Towards the end of the "viewForm", I have included another component named "footer" which contains 4 buttons that trigger different services to update values.

The challenge I am facing is adding validation to the input fields in the form (required), especially since the buttons are located in a different component than the form itself. Most examples I have come across focus on submit buttons or having both buttons and form in the same component. In my case, it is different. It seems like I need to set up validation for the form and then somehow pass this validation to the "footer" component to check before calling the service.

Below is a snippet of "viewForm":

<div>
  <div *ngFor="let point of points; let x = index">
    <mat-form-field class="example-full-width">
      <input matInput type="text" [(ngModel)]="point.cValue" Placeholder="">
    </mat-form-field>
  </div>
</div>
<app-footer></app-footer>

The structure of the footer component is as follows:

<footer class="footer">
        <div class="button-row">
            <button mat-raised-button (click)="save($event)">Save</button>
            <button mat-raised-button (click)="send($event)">Send</button>
            <button mat-raised-button (click)="noDeal($event)">No Deal</button>
            <button mat-raised-button (click)="deal($event)">Deal</button>
        </div>
    </footer>

Answer №1

When working with the viewForm Component:

It is important to make sure that public methods are available for validating the form input controls.

Within the footer Component:

@ViewChild(viewForm) vf: viewForm;

save(e){
  this.vf.validate();
}

send(e){
  this.vf.validate();
}

Answer №2

I utilized template-driven validation to solve this problem:

<form name="inspectionForm" #inspectionForm="ngForm">
    <div>
      <div *ngFor="let point of points; let x = index">
        <mat-form-field class="example-full-width">
          <input required matInput type="text" [(ngModel)]="point.cValue" Placeholder="" name="someName">
        </mat-form-field>
      </div>
    </div>
    <app-footer [formValid]="inspectionForm.form.valid"></app-footer>
</form>

In my footer component, I validate the form's validity status. Many thanks to Suresh for providing assistance.

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

Issue with FormControl bindings not functioning as expected for a particular FormGroup

I am experiencing an issue with my reactive form where I see null values for form controls under the alternate formGroup. Despite adding the attribute [formGroupName]="alternate" in the markup below, it does not appear to be working as expected. I also a ...

What is the process to activate/deactivate a drop-down menu once a radio button has been chosen

JSON Data: radio1Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, { value: 'col-2', viewValue: 'Col-2' } ]; radio2Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, ...

Get items from an array that have a property matching another array

Is there a more efficient way to create a new array with contact objects that have values matching those in selectedContact? selectedContact: number[] = [0,2] //value contacts: Contact[] = [{ firstName:"Dan"; lastName:"Chong"; email:"<a href="/c ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Encountering continuous loops during the resolution of sinon, hindering the ability to conduct proper unit testing in node

In an attempt to implement unit testing in Nodejs using sinon, I have recently installed the following libraries: 1 npm i mocha [2] npm i chai [3] npm i sinon Below is the code that I am working with: unitTest-app.js var sinon = require('sinon&a ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Issue with Angular/Jasmine: Undefined property 'pipe' not readable

I have been struggling to resolve a problem with Angular 9, Jasmine, and RxJS without much success. While my unit tests run successfully in Jasmine, there are certain lines of code that do not get executed. Despite scouring multiple posts for assistance, ...

Modifying elements in an array using iteration in typescript

I'm trying to figure out how to iterate over an array in TypeScript and modify the iterator if necessary. The TypeScript logic I have so far looks like this: for (let list_item of list) { if (list_item matches condition) { modify(list_ite ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

The tslint exclusion is not functioning properly for tsoa endpoints

I'm trying to remove the routes.ts file generated by tsoa routes from being compiled by tslint. I've used the exclude option but it doesn't seem to be working specifically for routes.ts. The exclude option works for other files, except for r ...

Is there a way to access a specific tab index in Ionic 3.20 from a child page using a function call?

Imagine having a tabs page with 3 index pages. The first index page is the home page, the second is the products page, and the third is the cart page. When navigating from the home page to the search page, there is a button that you want to click in orde ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

What method could I use to verify that my Angular 2+ login function has been invoked successfully?

Can anyone provide guidance on how to effectively verify if a function has been executed within the interaction of a component and a service? I welcome any insights or suggestions that can help me address this challenge! ...

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...

Can a TypeScript generator function be accurately typed with additional functionality?

Generator functions come with prototype properties that allow for the addition of behavior. The generated generators inherit this behavior. Unfortunately, TypeScript does not seem to recognize this feature, leaving me unsure of how to make it aware. For i ...

Navigating through pop-ups in Chrome: A guide to using Protractor

Currently, I am utilizing Protractor and am faced with the challenge of handling a pop-up from Chrome. My goal is to successfully click on the button labeled "Open magnet URI". For a visual representation of the issue, refer to the following image: picture ...

Table pagination in Mat is experiencing overflow, and the button styles have also been customized for a unique look

I implemented a mat paginator feature, however, I am facing an issue where the alignment of items per page options is not correct. Below is the snippet from component.html file: <div class="table-responsive" *ngIf="resultssummaries"> &l ...

Error with application tab directive based on user roles

My custom directive, the `has-role.directive.ts`, is responsible for displaying or hiding tabs in my application based on the user's role. However, I encountered an issue where after logging out, the directive fails to update the view and the tab rema ...

The test case for creating a component in Jasmine titled "should create" threw an error and failed with a TypeError stating: "FAILED TypeError: Cannot read property 'next' of undefined"

One of the key components in my application is responsible for fetching data from the store. @Component({ selector: 'iomt-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class ...