UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field called country in the form that, when updated, requires fetching a new set of validation rules. The issue I am facing is that the error messages for other fields do not update dynamically until I click on them. My goal is to have the error messages also updated automatically. Below you can see a snippet of my code. parentComponent.ts:

 // Setting validators for city
this.addressForm.get('city').setValidators([
  Validators.maxLength(this.labelStateService.recipientValidation.city.maxLength),
  Validators.pattern(this.labelStateService.recipientValidation.city.validationRegex),
  this.labelStateService.recipientValidation.city.required ? Validators.required : Validators.nullValidator,
]);
// Setting validators for fullName
this.addressForm.get('contact').get('fullName').setValidators([
  Validators.maxLength(this.labelStateService.recipientValidation.fullName.maxLength),
  this.labelStateService.recipientValidation.fullName.required ? Validators.required : Validators.nullValidator,
]);

ParentComponent.html:

<app-address-box [addressForm]="addressForm"></app-address-box>

Child Component.html

    <form [formGroup]="addressForm">
      <div class="form-floating-labels">
        <div class="row">
          <div class="col-sm-12">
            <div class="form-group">
              <select name="isoCountry" (change)="onCountryChange()" class="form-control" formControlName="isoCountry" [ngClass]="{
              'is-invalid':
                addressForm.get('addressForm').get('isoCountry').invalid &&
                (addressForm.get('addressForm').get('isoCountry').touched || submitted)
            }">
                <option *ngFor="let country of countries" [value]="country.alpha2Code">{{ country.shortName }} </option>
              </select>
              <label l10nTranslate for="isoCountry">ADDRESS.COUNTRY</label>
<p class="invalid-feedback">Enter a name.</p>
            </div>
          </div>

In conclusion, I am looking for a solution where the error messages for other fields in the formGroup get updated automatically upon updating the country field. Any assistance would be greatly appreciated!

Answer №1

To ensure your code functions properly, make sure you include the following additional lines:

 this.addressForm
                 .get('city')
                 .setValidators([
                   Validators.maxLength(this.labelStateService.recipientValidation.city.maxLength),
                   Validators.pattern(this.labelStateService.recipientValidation.city.validationRegex),
                   this.labelStateService.recipientValidation.city.required ? Validators.required : Validators.nullValidator,
                 ]);
               this.addressForm
                 .get('contact')
                 .get('fullName')
                 .setValidators([
                   Validators.maxLength(this.labelStateService.recipientValidation.fullName.maxLength),
                   this.labelStateService.recipientValidation.fullName.required ?
       Validators.required : Validators.nullValidator,
                 ]);


// Be sure to add these two lines as well
this.addressForm.get('city').updateValueAndValidity();
this.addressForm.get('contact').get('fullName').updateValueAndValidity();

Answer №2

Simplify your form validation process by using a single line of code that touches all of the form controls at once with the markAllAsTouched method:

this.form.markAllAsTouched();

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 could be causing the redirection to my php file in this particular contact form?

I have a contact form on my website that uses AJAX for submission. Everything seems to be working fine, but when the user clicks on the Submit button, they are redirected to the PHP file instead of staying on the page to see success or error messages. I wa ...

Using Typescript: Defining a property's type based on the value of another property in the same object

I'm dealing with a TypeScript interface that consists of two properties (type:string and args:object). The contents of the args property may vary based on the value of the type. I'm looking for the correct type definition to specify for the args ...

Is it possible to expand or merge Nestjs decorators?

My custom decorator named "User" is quite simple: export const User: () => ParameterDecorator = createParamDecorator( (data: any, req): UserIdentity => { const user = getUser(req); return user; }, ); Now, I'm in need of validating ...

I'm having trouble with one of my filter pipes not displaying any results. Can anyone help me troub

I have recently included a new filter for DL, but it seems that the results are not showing up as expected. Any ideas on what changes I should implement? <div class="form-group float-left mr-4"> <strong>DL</strong> <br /> ...

Error in SQL query: mistaking a value for a column name while updating a

Could someone explain why these code snippets are generating a SQL error? Error: Invalid column name Poe I seem to be unable to spot any issues in this code (except for perhaps the variable names) Updated code: index.cshtml if(IsPost) { var it = ...

Tips for inserting a line break within the output of an Angular pipe

Is there a way to display dates on separate lines in an Angular pipe? <th>{{(date | date: 'EEE MMM d')}}</th> Currently, the output is displayed like Mon Jul 20 - all in the same line. But I want it to be displayed like: Mon Jul ...

How can you implement Higher Order Components as a decorator in TypeScript?

Currently, I am attempting to develop a decorator that accepts an argument from React's Context provider. When creating a higher-order component (HOC), the process is straightforward: interface DashboardProps { user: User; } class Dashboard exten ...

Changes in the width of the left column in Bootstrap 4 are based on the content present in the right column

I seem to be struggling with implementing Bootstrap effectively. My goal is to achieve a layout similar to this, once the "Load Report" button is clicked and there is data to display: https://i.stack.imgur.com/c3nuO.png In the image, there are two column ...

What is the specific reference of the first parameter in NLS localize?

Regarding the question on localizing VSCode extensions, I am also curious why the localize function requires two parameters. When it comes to localizing settings, it's a simple process of replacing literal values with tokens surrounded by percent sig ...

After one second, my Ajax output is vanishing into thin air

Utilizing Ajax with a form, I have implemented an if condition for validation. If the form is empty, a message stating that all fields are required should be displayed. If the fields are filled, the data should be added to the database and a success messag ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

Obtaining the host and port information from a mongoose Connection

Currently, I am utilizing mongoose v5.7.1 to connect to MongoDb in NodeJS and I need to retrieve the host and port of the Connection. However, TypeScript is throwing an error stating "Property 'host' does not exist on type 'Connection'. ...

By default, all groups in the Kendo UI Angular 2 Grid are collapsed

Just started using the new Kendo UI for Angular 2 Grid and I have a question - is it possible to collapse all groups by default when grouping data? I noticed there is a method called collapseGroup(), but it's unclear how to use it or if there's ...

What is the best way to upload a photo taken with the Android camera using FormData in Ionic/Angular?

Currently in the process of developing an Android app that allows users to capture and upload their picture to a PATCH API endpoint with the key 'avatar'. To accomplish this, I am utilizing the Cordova Camera along with the Advanced HTTP plugin ...

Resolving the issue of 'type' property missing but required in 'SeriesXrangeOptions' within the Angular Highcharts module

I'm attempting to showcase a price chart view for a specific cryptocurrency chosen from a list of cryptocurrencies, but I keep encountering a type mismatch error. Within my application, I have utilized the angular-highcharts module and brought in the ...

Turn off or delete certain features within an npm package

Is it possible to disable or remove unused functions in a npm library? I only need certain functions from the library and don't want others to be accessible. I want to retain the read function while disabling the write function to prevent developers ...

Encountering a problem during npm installation on Windows 10 while trying to install the Angular CLI globally using the

node -v v4.5.0 npm -v 5.0.1 Is there anybody who encountered a similar problem when trying to install angular-cli on Windows 10? ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

Uploading an image with jQuery through Ajax form submission

When I try to add a new family member using a form with PHP and jQuery AJAX, the data gets posted but the image does not get uploaded. This is my HTML form that posts the data using AJAX (the issue is with the input type file): <form id="form_add_fami ...

Exploring Angular 10 Formly: How to Retrieve a Field's Value within a Personalized Formly Wrapper

Utilizing Angular 10, I have a formly-form with a select-field named session. This select field provides options from which to choose a dndSession. Each option holds key-value pairs within an object. I want to add a button next to the select-field that tr ...