Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disable a button on the parent component.

How can I access the forms and check their validity?

This code snippet is from the parent.html file

<div class="steps-content">
    <ng-template [cdkPortalOutlet]="componentPortal" (attached)=portalAttached($event)>
    </ng-template>
  </div>
    <button  nz-button (click)="pre(); $event.preventDefault()" [disabled]="current == 0 || processing" *ngIf="current < 4">
        <span nz-icon nzType="left"></span>
        Previous        
    </button>
    <button nz-button [disabled] = CHILDFORM.Invalid>   <---------- I need to set here
        Next
        <span nz-icon nzType="right"></span>
    </button> 

This section is from the parent.ts file

changeContent(): void {
      switch (this.current) {
        case 0: {
          this.index = 'First-content';
          this.componentPortal = new ComponentPortal(AssessmentCompanyFormComponent);
          this.cdr.detectChanges();
        break;
        }
        case 1: {
          this.index = 'Second-content';
          this.componentPortal = new ComponentPortal(AssessmentLocationFormComponent);
          this.cdr.detectChanges();
          break;
        }
        ...
      }
    }

portalAttached(_ref: CdkPortalOutletAttachedRef){
         this.ref = _ref as ComponentRef<any>;
         this.ref.instance.model = this.model; 
         this.ref.instance.assessmentOutput.subscribe(d =>{
          this.goToPage(d);
      })            
    }

And this is an excerpt from one of the child components mentioned above

export class AssessmentCompanyFormComponent implements OnInit {
  public validateForm: FormGroup = new FormGroup({});

Essentially, I want to disable the submit button on the parent component whenever the form in any child component has an invalid control.

Answer №1

If you're using ReactiveForms in your components, you can subscribe to the statusChanges of the formGroup.

In your components, you can define:

@ViewChild(FormGroupDirective,{static:true}) _form:NgForm

Then, you can use the following code snippet:

  portalAttached(event:any){
    setTimeout(()=>{
      const form=event.instance?._form?.form
      if (form)
        form.statusChanges.pipe(
          startWith(form.status),
          map(x=>x=='VALID'?true:false)
        ).subscribe((res:any)=>{
          ..you will receive true if valid, or false if invalid, pending, or disabled
        })
    })
  }

The setTimeout is enclosed to ensure that the form is checked after being attached.

For a demonstration, you can visit this stackblitz link.

NOTE: In the stackblitz example, I switched the "map" function logic to return false for valid and true in other cases, utilizing a variable named "disabled".

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

Ways to remove the default classes added by ngbootstrap

My current challenge involves utilizing ngbootstrap for popovers, yet desiring to override its default styling. Specifically, I have a form that should function as a popover triggered by a button click, and it needs to maintain its own distinct styles. Up ...

What could be the reason for the absence of the observable item value appearing in the HTML template?

Working with Angular4, I recently created a straightforward list-details example. However, when attempting to display item details on the details page, specifically for items of Observable type class, I encountered some obstacles. Below is the snippet of c ...

Having trouble building a new project with Angular-cli v.6?

I recently installed Angular CLI version 6 and created a new project following these steps: npm install -g @angular/cli@^6.0.0 ng new my-app cd my-app npm install npm build However, I encountered an error during the build process with the following messa ...

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

Decide on the Title based on a condition in Angular

To only set the title="" if a specific condition is true, and otherwise have no title at all, I need to ensure that the property.propertyKey === 'birthday' before assigning the value of birthday to the title. <div *ngFor="let ...

Declare a new variable with a specific data type in TypeScript

I'm working on creating a variable in my component of a specific type, as shown below. myrequest.model.ts export class MyRequest { public endValue: string; public yearEnd: string; } When importing the above into my component, I do the follow ...

Angular: Implementing conditional HTTP requests within a loop

Currently, I am facing a challenge where I need to loop through an array of objects, check a specific property of each object, and if it meets certain criteria, make an HTTP request to fetch additional data for that object. The code snippet below represen ...

Getting meta values in Angular2 is a common task that can be achieved through

Is there a way to retrieve the meta value from the HTML head in Angular2? For instance, let's say I have the following HTML structure of my project and I want to extract the meta tag with the name "userId". <!doctype html> <html> <he ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

"Error: Variable becomes undefined due to the implementation of async-await in TypeScript

There has been a persistent issue I've been dealing with for some time now. The problem lies in the fact that vm_res is undefined within the async update_vm_raw_device function despite the function running smoothly. As a result, the value being update ...

Creating a cutting-edge Angular 2 project with the power of webpack

Previously, I created a sample Angular 2 application using System JS for module loading, which was functioning properly. Now, I decided to switch to webpack module bundler instead of system JS and made the necessary changes. However, upon running the app ...

Error 404: Angular 2 reports a "Not Found" for the requested URL

I am currently in the process of integrating an Angular 2 application with a Java Spring Boot backend. As of now, I have placed my Angular 2 files under src/main/resources/static (which means that both the Angular and Spring apps are running within the sam ...

How can I utilize a variable as the value for ngClass in Angular 2?

Is there a way to use a variable in the ngClass value that gets added to the class list? I have a scenario where I have a set of image sprites, including a base sprite and an active state sprite with "-active" appended to the filename. I insert these sprit ...

Is it possible to execute TestCafe tests using TypeScript page objects that have not been utilized?

While working with TestCafe, I am implementing tests using the Page Objects pattern. I have already written some page objects in advance, even before their actual usage, as I am familiar with the page and know what to anticipate. However, when attempting ...

Error compiling SCSS in Angular 6 due to a util.js issue

As a novice in the world of Angular 6, I am currently exploring the Angular CLI and trying to grasp the file structure. My goal is to utilize SCSS for creating a unified global stylesheet. However, during compilation, an error keeps popping up: ERROR in . ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

Deploy the dist folder generated by ng build with the help of msdeploy

Has anyone successfully used msdeploy to install the output of ng build --prod (the dist folder) into IIS? I attempted to do so with this command: msdeploy.exe -verb:sync -source:package=c:\Workspace\MyProject\dist.zip -dest:auto -setPara ...

The concept of TypeScript usage within the `mui-x` DataGrid while calling the `useGridApiRef()` function

Could someone please help me understand the syntax used in this code snippet from mui/mui-x? export declare const useGridApiRef: <Api extends GridApiCommon = GridApiPro>() => React.MutableRefObject<Api>; My interpretation is that it exports ...