connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component.

For instance, I have a form for creating a user and I need to bind the validation of one field to the searchable-dropdown component.

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

}

I am trying to bind the validation for the roleId field in this component:

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

I attempted the following code to find validation of this form for roleId but it did not work for me:

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

fieldErrors(field: string): any {
    let controlState = this.formGroup.controls[field];
    return (controlState.dirty || controlState.touched) ? controlState.errors : null;
}

HTML :

    <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 [formControlName]="formcontrolName" (keyup)="getValues($event.target.value)" matInput
                    [placeholder]="'GENERAL.TITLE' | translate">
                <span *ngIf="fieldErrors(formcontrolName)" class="text-right">
                    <label *ngIf="fieldErrors(formcontrolName).required">WORKED</label>
                </span>
            </mat-form-field>
        </div>

How can I resolve this problem?

Answer №1

To enhance the functionality of this searchable-dropdown component, it is necessary to integrate a CustomValueAccessor.

As an illustration, consider a customized file component that can be utilized in reactive forms:

@Component({
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FileUploadComponent,
      multi: true
    }
  ]
})
export class FileUploadComponent implements ControlValueAccessor {
  @Input() progress;
  onChange: Function;
  private file: File | null = null;

  @HostListener('change', ['$event.target.files']) emitFiles( event: FileList ) {
    const file = event && event.item(0);
    this.onChange(file);
    this.file = file;
  }

  constructor( private host: ElementRef<HTMLInputElement> ) {
  }

  writeValue( value: null ) {
    // clear file input
    this.host.nativeElement.value = '';
    this.file = null;
  }

  registerOnChange( fn: Function ) {
    this.onChange = fn;
  }

  registerOnTouched( fn: Function ) {
  }

}

Refer to this informative blog post for a comprehensive guide on the implementation process.

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

Configuring the data source for an autocomplete feature in ReactJS Material UI

For one of my React components, I am utilizing the Material UI autocomplete feature. The data source is retrieved from the server asynchronously and has the following structure: const dataSource = [{ id: 001 firstName: 'fname', lastName: &apo ...

"Enhance readability by adjusting the font size on mobile devices and iPhones for an

I'm currently working on a website that needs to maintain a consistent look across all types of devices, including laptops, PCs, iPads, iPhones, and other smartphones. To achieve this, I've implemented fittext.js, a pure JavaScript solution that ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

ExpressJs Request Params Override Error

I am currently utilizing express version 4.19.2 (the latest available at the time of writing) This is how I have declared the generic type Request interface ParamsDictionary { [key: string]: string; } interface Request< P = core.ParamsDictionary, ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

What is the best way to utilize toggle("slide") in order to reveal a message letter by letter?

I am currently experimenting with the `.toggle("slide") function to create an effect where a piece of text appears as though each letter is sliding in. However, I've noticed that instead of a smooth slide, it looks more like the text is flying in abru ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

Ionic 6 prioritizes enhanced accessibility by implementing toast blocks that divert attention away from input fields

Scenario: My form is basic, but when the user tries to submit it with invalid inputs, I show a toast message with an error. Issue: Since upgrading to Ionic 6, I noticed that while the error toast is visible, I am unable to focus on any input fields until ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

Filtering Array Values within an Object using JavaScript

I need help filtering an object based on array values. For example: { "sun":["sleep","walk"], "mon":["read","dance","ride"], "tue":["work",&q ...

Utilize checkboxes for executing send operations and implementing prevention measures in Angular 9

I'm currently working with Angular 9 and I am facing an issue with a form that includes a checkbox. The form is designed in a way that when the user clicks the save button, it should fill in the name field. However, I have noticed that when the checkb ...

When implementing getStaticProps and getStaticPaths in a dynamic route, a 404 error page is displayed

As someone new to Next.js, I decided to delve into creating a basic news website where I could access articles through this specific route: /[category]/[article] The directory structure of pages is organized as follows: _pages __[category] ____index.jsx ...

MS Edge modifies the attribute's empty value to 1

I have written a JavaScript code to extract values from a list, but in the Windows Edge browser, it returns a value of 1 even when the actual value of the <li> tag is blank. For example: HTML Code <ul> <li value="">Test 1</li&g ...

Guide on establishing a connection with a TCP server and sending a JavaScript script to it

I am completely new to JS and node. I am using SkyX Pro, a telescope management software that has the capability to run a TCP Server on port 3040. By connecting with Netcat and providing it with Javascript starting with //* Javascript *//, I can control ca ...

Learn how to open a component in a new browser tab using Angular from a different component

I wish to display the MapComponent in a new browser tab when a button in my AppComponent html file is clicked. Currently, when I click the button, the MapComponent opens in a new tab but it also displays the button. How can I configure it so that only the ...

Automatically, the "ng-hide" class gets added despite using the correct syntax for ng-show

I am trying to dynamically show/hide a tr tag within a table based on the value of a scope variable in the controller. Despite writing the code correctly, I am facing an issue where the "ng-hide" class is automatically added to the tr tag every time it is ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...