Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into a separate component, the validation fails to work.

It is important to note that I only want to implement validation for files in certain components and not in others.

Please refer to this StackBlitz link to see the code example I have been experimenting with:

<form [formGroup]="formLocation" (ngSubmit)="onSubmitFarmLocation()">
    <div class="form-row">
        <div class="form-group col-sm-4">
            <label>Property Identification Number</label>
            <input class="form-control" type="text" formControlName="propertyIdentificationNumber"
                            [class.invalid]="!formLocation.controls['propertyIdentificationNumber'].valid && formLocation.controls['propertyIdentificationNumber'].touched " >
            <div
                *ngIf="!formLocation.controls['propertyIdentificationNumber'].valid && (formLocation.controls['propertyIdentificationNumber'].touched || isSubmitted)">
                <div class="invalid-feedback" style="display: block;">Please enter property identification
                    Number
                </div>
            </div>
        </div>
        <hr>
        <app-sharedfile></app-sharedfile>
        <div class="form-row">
            <div class=" ml-auto pb-3">
                <button type="submit" class="btn btn-primary" >Submit</button>
            </div>
        </div>
    </div>
</form>

Answer №1

To accomplish this task, you can utilize helper services along with a straightforward Subject without making extensive changes to your existing code.

For instance, consider a service called FileService that contains a Subject which can be accessed in the main component when the user clicks on the Save button.

export class FileService {
  checkFileUploadSubject = new Subject<boolean>();

  setCheckFileUploadValidity() {
    this.checkFileUploadSubject.next(true);
  }

  checkFileUploadValidity(): Observable<boolean> {
    return this.checkFileUploadSubject.asObservable();
  }
}

In the main component, you can inform the shared component by invoking the next method on the FileService Subject instance.

app.component.ts
 onSubmitFarmLocation() {
    this.isSubmitted = true;
    this.isShowErrors = true;
    this.fileService.setCheckFileUploadValidity();
    if (this.formLocation.invalid) {
      return;
    }

    console.log(this.formLocation.value, this.formLocation.errors);
  }

Subsequently, you can listen for events emitted by this Subject in your shared component and verify errors by marking FormControls as touched.

ngOnInit() {
    this.fileService.checkFileUploadValidity().subscribe(value => {
      debugger;
      this.formLocation.markAllAsTouched();
    });
  }

You can access the functional code sample here: https://stackblitz.com/edit/angularfi-leupload-xfpdfr

Answer №2

After setting up the ViewChild for SharedfileComponent like this:

@ViewChild(SharedfileComponent) child1Component: SharedfileComponent; 

You can simply call the validation from there using:

this.child1Component.formFiles.invalid
or
this.child1Component.formFiles.valid

To integrate it into your onSubmitFarmLocation method, just add the following code:

 onSubmitFarmLocation() {
    this.isSubmitted = true;
    this.isShowErrors = true;
    if (this.formLocation.invalid ) {
      return;
    }
    if (this.child1Component.formFiles.invalid) {
      console.log('form file invalid');
      return;
    }
    console.log(this.formLocation.value, this.formLocation.errors)
  
  }

Update:

If you want to display error messages in the shared component, ensure that you are using isSubmitted correctly in both HTML and TypeScript files. Refactor your onSubmitFarmLocation() method to return a boolean value based on form validity.

In sharedfile.component.ts:

onSubmitFarmLocation(): Boolean {
    this.isSubmitted = true;
    return this.formLocation.valid;  
  }

Then, in your component's submit logic, utilize this updated method like so:

onSubmitFarmLocation() {
  this.isSubmitted = true;
  this.isShowErrors = true;
  this.child1Component.onSubmitFarmLocation();
   
  if (this.formLocation.invalid ) {
    return;
  }
  if (this.child1Component.formLocation.invalid) {
    return;
  }

  console.log(this.formLocation.value, this.formLocation.errors)
}

For an updated demonstration, refer to this StackBlitz link: https://stackblitz.com/edit/angularfi-leupload-hvlegz

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

Provider in Angular2 that relies on multiple other Providers

Within my Angular2 application, I have various modules that offer Services and Configuration. Now, I want to integrate the @ngrx/store, which gathers reducers from all my modules. Below is the bootstrap code snippet: import {OpaqueToken} from 'angu ...

Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date? ...

Having trouble getting the Bootstrap toggle checkbox to function properly within Angular 2 components?

Working on an Angular 2 project with Bootstrap, I recently tried to integrate a bootstrap-toggle checkbox into the UI. Despite following the instructions from this site, the checkbox was displayed as a normal checkbox instead of toggled. The Index.html cod ...

The error message indicates that the 'aboutData' property is not found within the 'never[]' data type

What is the correct method for printing array elements without encountering the error message "Property 'post_title' does not exist on type 'never[]'?" How can interfaces be used to define variables and utilize them in code for both ab ...

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Supporting right-to-left (RTL) localization in Angular 2 and later versions

When it comes to incorporating right-to-left (RTL) support into a localized Angular 2+ application, particularly for languages like Hebrew and Arabic, what is considered the best approach? I have explored various tutorials, including Internationalization ...

Generate a data type automatically based on an Array

Imagine having an imaginary api that provides color values based on user selections. Consider the following arrays with string values: const Colors1 = ['red', 'blue', 'purple']; const Colors2 = ['blue', 'white& ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...

The argument with type 'void' cannot be assigned to a parameter with type 'Action'

Just getting started with Typescript and using VSCode. Encountering the following Error: *[ts] Argument of type 'void' is not assignable to parameter of type 'Action'. (parameter) action: void Here is the code snippet causing the err ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

Angular HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...

What is the reason behind the equality comparison between number[][number] and number in TypeScript?

https://i.stack.imgur.com/htnkb.png type Test = number[][]; // The Test type will be inferred as 'number' based on the image above. Can you explain why number[] is considered an index signature type with a signature of 'number'? ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

I am looking to update the color based on the prop value in React

Currently using react along with typescript. My objective is to adjust the color based on the value passed through props. The props will contain either "primary," "secondary," or "brand" as a string type. When the value "primary" is provided, I aim ...

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

A guide on implementing RxJS Observables to target a specific DIV element

Currently, I am working with Angular 2. At the moment, I have been using this method to select a specific DIV element: <div #aaa> </div> @ViewChild('aaa') private aaa: ElementRef; ngAfterViewInit() { let item = this.aaa.nativeEle ...

Assign a value to ReplaySubject if it is currently devoid of any

I am facing a challenge with my ReplaySubject in the component after content initialization. Whenever it initializes, it always gets set to "/api/bulletin/getall" value and overrides any value assigned to it before in the onViewChanged function. How can ...

Discovering the file system with window.resolveLocalFileSystemURL in Typescript for Ionic 3

After reviewing the documentation found on this link for the File plugin, I came across a paragraph that discusses how to add data to a log file. See the example code below: window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...