Validation of ngModel in Angular for a subcomponent form

One of the components I'm working on has a model structured like this:

model={
name,
surname,
age,
birthDate
}

I am passing this model to a sub-component.

<form #form="ngForm" >
<input name="name" [(ngModel)]="model.name" required>
<input name="surname" [(ngModel)]="model.surname" required>
<sub-component #sub="ngModel" [(ngModel)]="model"></sub-component>
<button [disabled]="form.invalid" (click)="addOrUpdate()" ></button>
</form>

The sub-component looks like this:

<input name="age" [(ngModel)]="model.age" required>
<input name="birthDate" [(ngModel)]="model.birthDate> // not required

When checking the validation in the parent component using 'sub.valid', it always appears valid. However, in the sub-component, if 'model.age' is null, the validation is invalid. I want the sub-component's validity to affect the parent component's validity so that the parent's button can be disabled when necessary.

I have tried importing Control Value Accessor and providing NG_VALUE_ACCESSOR but it didn't solve the issue. The code snippets provided are just for illustration purposes - my actual model is much larger. I also attempted implementing the Validator interface and validate function, but found it to be a cumbersome solution.

Answer №1

Consider incorporating a form tag within the sub-component:

<form #form="ngForm">
  <input name="age" [(ngModel)]="model.age" required>
  <input name="birthDate" [(ngModel)]="model.birthDate"> // not required
</form>
@ViewChild('form') public form: NgForm;

In the parent component template, access the subcomponent's form to verify if the subcomponent's form is invalid:

<sub-component #sub [model]="model"></sub-component>
<button [disabled]="sub.form?.invalid" (click)="addOrUpdate()" ></button>

This technique can be beneficial.

Answer №2

Is it possible to implement the following code snippet?

<form #form="ngForm">
<sub-component #sub [model]="model"></sub-component>
<button [disabled]="form.invalid" (click)="addOrUpdate()" ></button>
</form>

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

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

The error was thrown at line 883 in the cjs/loader.js file of the

I'm encountering an error when trying to run npm start (I've included a screenshot of the error below) in my Angular project. However, everything works fine when I use ng serve. I've attempted multiple solutions to resolve this issue with ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Whenever I try to access my Node.js API from Heroku's live server, I encounter a CORS policy error

Whenever I try to access my Node.js API from the Angular app (running on a local setup) and host the API on Heroku's live server, I encounter the following error: CORS policy: No 'Access-Control-Allow-Origin'. Interestingly, when I host the ...

Retrieve and showcase data using Ionic 2's local storage functionality

Hi, I'm having trouble accessing my data in local storage. Every time I try, it gives me an error. I need assistance with displaying my data at home. Thank you for your help :) Error: Typescript Error Argument of type 'Promise' is not assi ...

Error in Redirecting to Localhost

Recently, I developed an Angular App that interacts with the MS Graph API using MSAL. Initially, everything worked smoothly when running "ng serve" in Angular CLI. However, I encountered a problem when I packaged this Angular App with electron to deploy i ...

Angular: accessing public properties

I have a component called "user.service.ts" that I want to share. import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { AppConfig } from '../app.config&apos ...

Requiring Additional d3 Plugins in d3 v4 Extension: A guide

I am currently working on developing a d3 v4 plugin by following the guidelines provided at . My main objective is to be able to npm install the plugin and seamlessly use it within an Angular 2/4 component. The repository for my project can be found here: ...

Enhancing Request JSON Body Validation in Next.js 14 API Handler

I'm currently in the process of developing an API for my iOS application using Next.js 14. I have managed to get it up and running successfully, however, I am facing some challenges when it comes to properly validating the body of a request. ESLint is ...

Implementing Vuex 4 modules within Vue 3 using TypeScript and troubleshooting the cyclical dependency linting issue

Vue 3.0 has recently launched its stable v3.0.0 'One Piece' release, while Vuex 4 is currently in v4.0.0-beta.4. Although official examples on utilizing Vuex 4 modules in TypeScript are lacking... For better code management as modules expand, I ...

The Angular overlay is concealed beneath the pinned header

I am seeking a solution to have a mat-spinner displayed on top of my app while it is in the loading state. Currently, I am using an overlay component with Overlay from @angular/cdk/overlay. The issue arises when part of the spinner that should be overlai ...

Initial request to Angular HTTP does not return a value

Upon the initial function call, it does not return anything. However, upon subsequent attempts, it returns valid data. I am unsure why this is happening of my own knowledge. Here is an excerpt from My Exam: getUserAccountInfo(token: string | null): Obser ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

The `HubConnection` class constructor is restricted to private access and can only be accessed within its class declaration

Currently, I am in the process of integrating an Angular and SignalR project. The guidance I am following comes from a resource on Medium. I have successfully installed all essential packages and included the code snippet below in my app.component.ts file ...

Tips on triggering a function when an Ionic or HTML event is initiated

I am facing a scenario on my HTML page where I need to display certain data when an if condition returns False, and execute a function when the condition returns true. However, I'm unsure about how to achieve this. <ng-container *ngIf="!(form.answ ...

Issue with Angular Material: Default selection not being applied in mat-select component

When I have a mat-select with options defined as objects in an array, I am facing an issue where the default selected value is not being set when the page renders. In my TypeScript file, I have: public options2 = [ {"id": 1, "name": "a"}, {"id": 2 ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Using AsyncPipe within an ngFor loop to display items

What is the best practice for using an AsyncPipe within an ngFor loop to handle asynchronous calls for items in a list? Scenario: Imagine I have an Order object with Products, and I need to display each product's manufacturer. However, the manufactur ...

Creating an image using the @aws-sdk/client-bedrock-runtime package is a simple process

Having crafted a BedrockRuntimeClient using typescript, I'm stumped on how to call upon the model and execute the command. const client = new BedrockRuntimeClient({ region: "us-east-1", apiVersion: '2023-09-30', ...