connect the validation of forms to different components

I am currently working on components to facilitate the user addition process.

Below is an example of my form component:

createForm(): void {
    this.courseAddForm = this.formBuilder.group({
        name: ['', [
            Validators.required,
            Validators.maxLength(this.val.maxLen.title)
        ]],
        roleId: ['', Validators.compose([Validators.required])]
    });
}

name : represents the username,

roleId : is a field for selecting a role from a dropdown menu.

I have created a component called <kt-searchable-dropdown> specifically for the roleId selection.

The HTML structure is outlined below:

       <form id="courseAddForm" [formGroup]="courseAddForm" (ngSubmit)="onSubmit()" autocomplete="off">
                <div class="form-group kt-form__group row">
                    <!-- title -->
                    <div class="col-lg-6 kt-margin-bottom-20-mobile">
                        <mat-form-field class="mat-form-field-fluid" appearance="outline">
                            <mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
                            <input matInput formControlName="title" [placeholder]="'GENERAL.TITLE' | translate">
                            <!--required error-->
                            <mat-error *ngIf="courseAddForm.get('title').errors?.required">
                                {{ 'VALIDATION.REQUIRED.TITLE' | translate }}</mat-error>
                            <!--length error-->
                            <mat-error *ngIf="courseAddForm.get('title').errors?.maxlength">
                                {{'VALIDATION.MAX_LENGTH' | translate}} {{val.maxLen.title}}
                            </mat-error>
                        </mat-form-field>
                    </div>

                    <div class="col-lg-6 kt-margin-bottom-20-mobile">
                        <kt-searchable-dropdown [formGroup]="courseAddForm" [formcontrolName]="'courseId'" (selectedId)="selectedCourse($event)"
                            [formTitle]="'COURSE.COURSE_GROUP'" [url]="url"></kt-searchable-dropdown>
                    </div>

                </div>
            </form>

I also have a custom component for handling the roleId dropdown selection:

In the TypeScript file:

export class SearchableDropdownComponent implements OnInit {

@Input() url: string;
@Input() formTitle: string;
@Input() ItemId: number;
@Input() formcontrolName: string;
@Input() formGroup: FormGroup;
@Output() selectedId = new EventEmitter<number>();

loading = false;
values: KeyValue[];
title: string;
fC: FormControl;

constructor(
    private searchService: SearchableDropDownService,
    private cdRef: ChangeDetectorRef) {

}

ngOnInit(): void {
    this.getValues(null);
}

getValues(event): void {

    this.cdRef.detectChanges();
    this.loading = true;

    let model = {} as SendDateModel;
    model.page = 1;
    model.pageSize = 60;
    model.title = event;

    this.searchService.getAll(this.url, model).subscribe(data => {
        this.values = data['result']['records'];
        this.cdRef.detectChanges();
        this.loading = false;
    });

}
}

In the HTML file:

<form [formGroup]="formGroup">
<mat-form-field appearance="outline">
    <mat-label>{{formTitle| translate}} *</mat-label>
    <mat-select formControlName="courseId" >
        <div class="col-lg-12 mt-4 kt-margin-bottom-20-mobile">
            <mat-form-field class="mat-form-field-fluid" appearance="outline">
                <mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
                <input (keyup)="getValues($event.target.value)" matInput
                    [placeholder]="'GENERAL.TITLE' | translate">
            </mat-form-field>
        </div>
        <mat-progress-bar *ngIf="loading" class="mb-2" mode="indeterminate"></mat-progress-bar>
        <mat-option  (click)="emitdata(item.key)" *ngFor="let item of values"
            [(ngModel)]="ItemId" [value]="item.key">
            {{item.value}}
        </mat-option>
        <mat-error *ngIf="formGroup.get('courseId').errors?.required">
            {{ 'COURSE.VALIDATIONS.REQUIRED.CLASS_LEVEL' | translate }}</mat-error>
    </mat-select>
</mat-form-field>

However, I am encountering issues with the code implementation.

I am looking to implement validation binding in the form within these components. For instance, when the roleId field is required and the user does not select an item, an error should be displayed indicating that the roleId is mandatory. I would like to integrate this functionality into the SearchableDropdownComponent. How can I achieve this?

Answer №1

To implement this functionality, utilize angular observables. Develop a service to manage the error state in your primary component.

ErrorService.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/BehaviorSubject';

@Injectable()
export class ErrorService {

  private errorObj = new Subject<any>({});
  data = this.errorObj.asObservable();

  constructor() { }

  updatedErrorObj(error){
    this.errorObj.next(error);
  }

  getErrorObj(){
    return this.errorObj.asObservable();
  }
}

In the first component, instantiate this service and update the error object when an error occurs.

FirstComponent.ts

// Initialize the service in the constructor
constructor(private errorService: ErrorService) { }
onSubmit() {
    if(this.courseAddForm.invalid) {
        // Update error object
        cont errorObject = { key: 'value' }; //Define custom error object here
        this.errorService.updatedErrorObj(errorObject);

    }
}

Capture this error in the SearchableDropdownComponent

// Initialize the service in the constructor
constructor(private errorService: ErrorService) {
    errorService.getErrorObj.subscribe(data => {
      // Handle actions upon data changes
      // Receive the error object here.
    })
}

For more details, refer to this blog post.

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

Verify image loading using jQuery

<img src="newimage.jpg" alt="thumbnail" /> I am dynamically updating the src attribute of this image. Is there a way to verify if the image has been successfully loaded and take action once it is? Appreciate any guidance on this matter. ...

The inclusion of <script> tag within the response received from an Ajax

Is there a way to update an element's innerHTML using Ajax.request that includes <script> tags? <div><script type="text/javascript">javascript</script></div> I want to update the content of a div with code from above wi ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

What is the best way to change the value of a boolean array in React?

In my component, I maintain an array of boolean values as a state. When the value is false, I need to change it to true. this.state = { checkedPos: [] } handleChange(index, reaction) { if (!this.state.checkedPos[index]) { this.state.ch ...

Angular 2 Guide on macOS Sierra Shows "Page Not Found" Error in Web Browser

I've been delving into Angular 2 with TypeScript on my OS X machine. Following the tutorial to the T, I didn't encounter any errors during compilation. Upon executing the npm start command, everything seemed to be smooth sailing as a new tab open ...

Dealing with 404 errors: The role of Nuxt.js and the srcDir option in handling URL

By incorporating the srcDir option into my nuxt.config.js file, I made the decision to transfer the pages, components, and layouts folders to the src directory. Below is how my configuration looks: module.exports = { srcDir: 'src', head: { ...

What is the mechanism behind JQuery Ajax?

Currently, I am attempting to utilize JQuery Ajax to send data to a Generic Handler for calculation and result retrieval. Within my JQuery script, the Ajax request is contained within a for loop. The structure of the code resembles the following: function ...

While iterating over each item in the List<string> retrieved from an AJAX GET request in JavaScript

Trying to iterate through a list of strings and display them on the page, but facing an error as described in the title... "Uncaught TypeError: response.forEach is not a function" I've looked into for loops in JavaScript, but they seem to work wit ...

Error Encountered when Attempting to Retry AI SDK on Vercel's

I've been implementing code from the official AI SDK website but unfortunately, the code is not functioning properly. The error message I'm encountering is: RetryError [AI_RetryError]: Failed after 3 attempts. Last error: Failed to process error ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Struggling to get the Okta Auth0's AuthGuard to properly redirect to a specific route following a successful login request for a protected route

I have implemented Auth0 in my Angular application to authenticate users using the steps outlined below: Users visit the root page (e.g. ) and click on the Login button via their Google account. Users are redirected to the Auth0 login page through the Goo ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

In Nextjs, it is possible to extend a page just like creating a nested switch in react-router-dom. This functionality

After spending some time using React, I recently decided to experiment with NextJS. Currently, I am working on a dashboard project that includes a side navigation menu, which will be used across multiple pages. In ReactJS, I typically create a nested switc ...

What could be causing redux.props.reducer to return undefined?

I recently encountered an issue with my code. I have a function in the actions folder that successfully fetches a URL using axios. However, there seems to be a problem when trying to retrieve the data from the reducer. I have a mapStateToProps function set ...

Show one marker on the map from a GeoJson file

On my webpage, I have a Google map that displays all markers using the map.data.loadGeoJson method. Each marker is linked to its respective details page with the following code: map.data.addListener('click', function(event) { var id = even ...

Can a function utilize a Generic-specified type property?

function extractStringValue<T extends object, S extends keyof PickByValue<T, string>>( obj: T, key: S ): string { return obj[key]; }; The PickByValue function extracts properties of object T with values of type string. type CustomType = ...

JavaScript class with callback function commonly used

I am looking to create a JavaScript class that can register multiple functions to run with a common callback. Each registered function should run asynchronously, and once they have all completed, the specified callback function should be executed. In addi ...

Issues encountered when attempting to utilize ng-autocomplete 2

Attempting to implement ng2-autocomplete by following the documentation at https://www.npmjs.com/package/ng2-completer I have been encountering various errors every time I attempt solutions from Stack Overflow or GitHub. Any assistance in resolving this i ...

Tips for resolving the problem when encountering the "undefined data" issue in the success callback of an AJAX request

I am facing an issue with my JSP page where I have a button that calls an Ajax method named "sendmail()" upon click. The send mail API is in the Controller, and I am trying to display an alert message in the Ajax success function using data.message, but it ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...