Only implement valueChanges on the second step of the form

I am utilizing the mat-stepper with a single form. My stepper has two steps only. I am looking to make an API request for every input value change, but only when the user is on the second step. How can I accomplish this?

.ts

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          "product": ['lifeci', Validators.required],
          "gender": ['', Validators.required],
          "birthDate": ['', [Validators.min(18), Validators.max(50)]],
          "payFrequency": [12],
          "subLimit": ['100']
        }),
        this._formBuilder.group({
          "currency": ['USD', Validators.required],
          "amount": ['15000', Validators.required],
          "period": ['', Validators.required],
        }),
      ])
    });
    //send request onchange
    this.formGroup.valueChanges.subscribe(val => {
      this.onSubmit();
    });
  }

In terms of HTML, I am following the same structure as outlined in the documentation.

Answer №1

Subscribe solely to the second segment of the form's progression

(this.formGroup.get('formArray') as FormArray).at(1).valueChanges.subscribe(val => {
      this.onSubmit();
    });
  }

Answer №2

To start, introduce a new variable currentTab in your TypeScript file.

const currentTab = 0;

Next, include the currentTab input directive in your stepper component:

<mat-horizontal-stepper [currentTab]="selectedTabIndex">

Lastly, update the subscription method for valueChanges as follows:

this.formGroup.valueChanges.subscribe(value => {
    if (currentTab === 1) {// Indicates that the second tab is selected
        this.onSubmit();
    }
});

Answer №3

In order to effectively operate within a specific form, it is recommended to separate each step into its own "semi-form" using getters.

Start by defining an enum or type in your component file that outlines each step of the form.

enum FormStep {
  BorrowerDetails = 0,
  LoanDetails = 1
}

In your component class, create getters for each step.

private get borrowerDetailsForm() {
  return (this.formGroup.get('formArray') as FormArray).at(FormStep.BorrowerDetails);
}

private get loanDetailsForm() {
  return (this.formGroup.get('formArray') as FormArray).at(FormStep.LoanDetails);
}

With these getters established, you can easily access and manipulate each step of the form within your component.

this.loanDetailsForm.valueChanges.subscribe(() => this.onSubmit());

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

Injecting Services Error in Angular

I'm in the process of developing a web App and recently put together a new service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ModuleService { constructor(private startTime: ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Transform Typescript code into Javascript using webpack while preserving the folder organization

Is there a way for webpack to compile my typescript node project into js while preserving the directory structure and not bundling into one file? This is my current project structure: src |_controllers |_home |_index.ts |_ services ...

Unit testing Firebase function with Jest for mocking

Currently, I am in the process of developing unit tests and facing challenges with mocking Firebase functions while specifying the return type upon calling them. The code snippet below illustrates what I intend to mock (account.service.ts) and provides ins ...

Creating dynamic Kafka topic names within a NestJS microservice

Currently in Nestjs, I have integrated Kafka as my message broker and specified the topic name like so: @MessagePattern('topic-name') async getNewRequest(@Payload() message: any): Promise<void> { // my implementation logic } I am curious ...

The module 'AppModule' has imported an unexpected pipe. To resolve this issue, please include a @NgModule annotation

I have successfully created a custom pipe to remove duplicate items from an array and have imported it into my app.module.ts file Below is the code snippet: app.module.ts import { UniquePipe } from './_pipe/uniquePipe'; @NgModule({ imports: ...

How to display specific JSON objects that meet particular criteria in HTML cards using Ionic and Angular?

As a beginner in Ionic/Angular, I am attempting to fetch data from a JSON file and display it using cards in the HTML. The JSON contains numerous objects that are either marked as "deTurno == true" or "deTurno == false". Here is what I have so far: publi ...

Transform angularjs directive into angular 10

After stumbling upon this intriguing code snippet, I decided to integrate it into my angular project: 'use strict'; /** * A mesmerizing floating text animation */ angular.module('g1b.text-animation', []). directive('textAnimatio ...

Errors in typing occurring due to preact children within framer-motion

While working on my preact widget (https://github.com/preactjs-templates/widget), I noticed a connection to ReactDOM. import { motion } from 'framer-motion'; import { h, VNode } from 'preact'; const Test = () => { return <mot ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Error Encountered: Anticipated 'styles' to consist of a series of string elements

I have attempted various solutions for this particular error message without any success. When launching my angular project using the angular cli via ng serve, everything runs smoothly with no errors. However, upon compiling it with webpack, I encounter th ...

Encountering an uncaught SyntaxError due to an unexpected token < while working with AngularJS2 on a local

I am currently facing an issue while trying to run my angularjs2 project locally using nodejs. I can successfully run it using npm start but encountering errors when attempting to use node app.js. The error message that pops up states: "systemjs.config.js ...

Issue with tooltip not displaying attribute data-bs-title in Angular 17 with Bootstrap version 5.3

I am currently developing an Angular version 17 application and implementing a dynamic tooltip feature. The tooltip content will be supplied through a @Input() into the component. While a static tooltip works fine, I am facing an issue when trying to make ...

What is the best way to loop through the keys of a generic object in TypeScript?

When I come across a large object of unknown size, my usual approach is to iterate over it. In the past, I've used generators and custom Symbol.iterator functions to make these objects iterable with a for..of loop. However, in the ever-evolving world ...

Tips for utilizing multiple components in Angular 2

I am a beginner in angular2 and I am attempting to utilize two components on a single page, but I keep encountering a 404 error. Here are my two .ts files: app.ts import {Component, View, bootstrap} from 'angular2/angular2'; import {events} f ...