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

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

Awaitable HttpResponseError

My challenge is that I'm attempting to handle a HttpError or HttpErrorResponse using an observable. However, the only option I have is to handle the HttpResponse, which is necessary but not sufficient. I also need to find a way to avoid this limitatio ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Opening a modal from a different component in Angular 6

I am attempting to launch a modal that is associated with a separate component. However, I encountered an error ERROR TypeError: Cannot read property 'show' of undefined Here is my code: product-catalog.component.html <app-cart-table-modal& ...

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

Error message: Angular encountered a SyntaxError when parsing JSON data due to an unexpected character at the beginning of the data

Encountering SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data After validating the JSON, it was discovered that the error lies in: let json = JSON.stringify(user); let params = "json="+json; // The error se ...

Is there a way to determine the total number of angular components in my app using IntelliJ IDE?

Seeking a way to determine the total count of angular components using IntelliJ IDE. I attempted 'find in files' search tool with the terms "export class" but it retrieved more than just component files. Appreciate any help! =) Etienne. ...

Adding multiple classes to a condition in Angular can be achieved by using the ngClass directive

Here is the code snippet I am working with: <div *ngFor="let d of getDays(); let i = index" class="day hr left" (click)="pick(d, h)" [class.white]="days[d].indexOf(h) > -1"> </div> Everything seems to be working well, but I have a ques ...

What is the method for accessing a validator that has been declared in a reactive form group while within the scope of a custom

Currently, I have a custom component that I am happy with and it is being used in a reactive form as shown below. private init() { const control4 = new FormControl("yy", Validators.pattern(".{2}")); const control5 = new FormControl("zz", Validators.pa ...

Secure your NetSuite API calls with OAuth 1.0 signature authorization

After extensively reviewing the documentation and various posts on Stack Overflow about creating a signature for NetSuite OAuth1.0 with TBA, I believe that I have followed all of the necessary steps and correctly generated the key. However, upon making the ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

Do not send the Angular 2 HTTP request with headers

As someone new to Angular2, I am working on building a data service and trying to include headers in each request. Here is my attempt at adding headers, but for some reason they are not being sent: import { Injectable } from '@angular/core'; im ...

Issue with Angular 8: discrepancy between the value utilized in component.html and the value stored in component.ts (Azure application service)

Encountering a peculiar behavior in one of my Angular applications. In the component.html file, I aim to display "UAT" and style the Angular mat elements with a vibrant orange color when in UAT mode, while displaying them in blue without any mention of UAT ...

Error: Prisma seed - encountering issues with undefined properties (unable to read 'findFirst')

I've encountered a strange issue when using prisma seed in my nextjs full-stack project that I can't seem to figure out. Normally, when running the app with `next dev`, everything works smoothly and the queries are executed without any problems. ...

Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example: import * as models from '../../view-models/models' ....... let parrot: m ...

What is the best way to accurately parse a Date object within a TypeScript class when the HttpClient mapping is not working correctly?

Task.ts: export class Task { name: string; dueDate: Date; } tasks.service.ts: @Injectable() export class TasksService { constructor(private http: HttpClient) { } getTasks(): Observable<Task[]> { return this.http.get<Ta ...

Troubleshooting Angular2 Router: Version 3.0.0-alpha.8 - Issue with resolving parameters for provideRouter function

Encountering an issue while working on a project in angular2 with router version "3.0.0-alpha.8". The error message displayed during the loading of APIs states: Can't resolve all parameters for provideRouter: (?, ?) . Error : BaseException$1@http:// ...

Error: `__WEBPACK_IMPORTED_MODULE_1_signature_pad__` does not function as a constructor

I recently discovered the angular2-signature-pad library for capturing signatures in my Angular project. I attempted to integrate the library using the following steps: // in .module.ts file import {SignaturePadModule} from "angular2-signature-pad"; @NgMo ...

What could be causing the first() rxjs operator to repeatedly return an array?

I'm currently facing an issue with a service that has the following function signature: getSummary(id: string, universe: string): Observable<INTsummary[]> My requirement is to retrieve only the first item in the INTsummary[] array when calling ...