Is it possible to validate input from a parent component in Angular and pass it on to a nested child component?

I have a form with reactive validation where the submit button is in the grandparent component. I am trying to figure out how to check the validation status of my child component using ViewChild or any other method. It seems like an impossible task to me, so I need some help solving this issue.

Child Component:

<form [formGroup]="headerForm"></form>

Parent Component:

<app-header
  [countries]="countries$ | async"
  [products]="products$ | async"
  [statuses]="statuses$ | async"
  (headerChanged)="getHeaderInformation($event)"
>
</app-header>

Grandparent Component:

  <app-header-shell
    (headerShellChanged)="updateRegulatoryAffairShell($event)"
  ></app-header-shell>

Even though I am passing data between components using @Output, I am struggling to check the validation status. Any assistance would be greatly appreciated.

 @Output() headerShellChanged = new EventEmitter<IRegulatoryAffair>();

  getHeaderInformation(regulatoryAffair: IRegulatoryAffair) {
    this.headerShellChanged.emit(regulatoryAffair);
  }

Answer №1

To give the component a template Ref, follow these steps:

<app-header
  #appHeaderComponent
  [countries]="countries$ | async"
  [products]="products$ | async"
  [statuses]="statuses$ | async"
  (headerChanged)="getHeaderInformation($event)"
>
</app-header>

Next, in the grandParent component, declare the entire component as a ViewChild:

@ViewChild('appHeaderComponent') appHeaderComponent: AppHeaderComponent

Now you can access the entire component and utilize any property or method like so:

this.appHeaderComponent.headerForm.markAllAsTouched();
this.appHeaderComponent.headerForm.valid ? this.doSubmit() : return;

For instance, you can also handle individual form controls' state as shown below:

this.appHeaderComponent.headerForm.get('myControl').setValidators([Validators.required]);

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

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

What is the proper way to arrange dates within strings in Angular?

I'm currently facing an issue with sorting two strings. The strings in question are: "2022 | Dec (V2 2022)" "2022 | Jul (V1 2022)" Although I am attempting to sort them using localeCompare, it is not yielding the correct result. T ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Incorrect Node.js version identified

I have been facing a challenge trying to integrate my projects developed with Spring and Angular using Maven. The issue arises with the Node.js version: [ERROR] Node.js version v8.11.3 detected. [ERROR] The Angular CLI requires a minimum Node.js version of ...

Develop an original angular material theme utilizing CSS variables

I have been working on a project that requires runtime theming. To achieve this, I developed a theme system that combines SCSS variables with CSS Variables. Here's an example of how it functions. :root { --primary-color: 196; } // Primary $primary ...

An issue arises in TypeScript when targetting ES5 and utilizing Async Iteration, causing errors while running in the browser

After reading through the documentation on "Generation and Iteration for ES5", I implemented this polyfill: (Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator"); However, upon doing so, my browser encountered an erro ...

Utilizing a personalized URL path in Spring Boot and Maven for backend responses leads to a whitelabel error

I am currently working on two separate projects, one being a projectApi (backend developed in Spring) and the other a projectUi (frontend developed in Angular). To combine these two projects into a single jar for production, I am using the maven-resource-p ...

From transitioning from AngularJS to the latest version Angular 8

I have an Angular application where I need to update some old AngularJS code to work with Angular table.html <table ngFor="let group of vm.groups" style="float: left"> <thead> <tr> <th><b>Sl. No</b ...

The deprecation of DynamicComponentLoader in Angular 2 rc4 is now in effect

I am currently in the process of updating my Angular 2 application from beta.14 to rc.4. Upon moving to @angular/core, I encountered a deprecated warning related to DynamicComponentLoader. Can someone provide guidance on the new Class that should be used ...

Using TypeScript to define multiple extended conditions in a single line

Currently in the process of converting my javascript project to typescript, and I must say, the learning stage has been quite enlightening. Converting the project has taught me a lot so far. While I did encounter a challenge in my code which I managed to r ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...

Obtaining client system details in an Angular application

Hey there! I'm looking to retrieve the client system information using Angular, could someone please guide me on how to do this? System Information Model Serial Number Operating System Details OS Type Architecture Host Name CPU Specifications ...

The functionality of verifying the type of an item in a list using Typescript is not functioning

In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff. type NameValue = { name: string; value: string }; type MixedStuff = NameValue | string; function stripTwoChars(stuffs: MixedStuff[]): string { let st ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

The error with removing the form field control in Angular 7 persists

I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure of the FormGroup: ngOnInit() { this.basicInfo ...

How should I structure my MySQL tables for efficiently storing a user's preferences in a map format?

My current project involves developing a web application that provides administrators with the ability to manage user information and access within the system. While most user details like name, email, and workID are straightforward, I am facing difficulty ...

Testing Angular directives; clicking on an element does not result in a click on the document

By implementing a directive, I am able to determine if there has been a mousedown event that occurred outside of the specified element. This is accomplished using an observable: @Output() clickOutside = new EventEmitter<void>(); constructor(priva ...

The Angular 6 watcher fails to compile the imported less files within the main.less file

Currently, I am developing in Angular version 6 and utilizing Less for styling purposes. In previous Angular versions, I utilized the angular_cli.json file to include the main Less file, which functioned properly. Now, in the latest Angular 6 version, I ...

Encountering an error when trying to declare a type in VSCode with ESlint and React Types

After setting up an axios configuration file with proper typing support, I encountered the following error message: import axios, { AxiosRequestConfig, AxiosInstance } from 'axios'; const api = axios.create({ baseURL: '/api', resp ...

The angular2-highcharts package encountered an error while trying to statically resolve symbol values

I'm facing an issue with the plugin while trying to use it in different ways. Whenever I mention "ChartModule.forRoot (require ('highcharts'))," it results in this exception import { ChartModule } from 'angular2-highcharts'; impo ...