Ways to incorporate forms.value .dirty into an if statement for an Angular reactive form

I'm a beginner with Angular and I'm working with reactive Angular forms. In my form, I have two password fields and I want to ensure that only one password is updated at a time. If someone tries to edit both Password1 and Password2 input fields simultaneously, an alert should be triggered saying "Update password one by one."

form.component.html

<form [formGroup]="xyzGroup>
     <div class="form-group row">
                <label for="password" class="col-sm-3">Password1:</label>
                <div class="mx-sm-2 text-center">
                    <input type="password" class="form-control-sm" 
                     formControlName="WifiPassword" [(ngModel)]="password1" id="inputPassword">
                </div>
            </div>
     <div class="form-group row">
                <label for="password" class="col-sm-3">Password2:</label>
                <div class="mx-sm-2 text-center">
                    <input type="password2" class="form-control-sm" 
                     formControlName="WifiPassword2" [(ngModel)]="password2" id="inputPassword">
                </div>
            </div>
<button (click)=onAlert()>Submit</button>
</form>

form.component.ts

ngOninit(){
this.setFormGroup();
}

 setFormGroup() {
    this.xyzGroup = this.fb.group({
      WifiPassword: "",
      WifiPassword2: "" })
}

onAlert(){
   if(this.xyzGroup.value.WifiPassword.dirty && this.wlanSettingsGroup.value.WifiPassword2.dirty){
   alert("update password once at time")
     }
else{
  here i am using submit method.......
}

In the code, I'm having issues with the condition inside `if(this.xyzGroup.value.WifiPassword.dirty)`. Can anyone assist me with this problem?

Answer №1

It appears that your form is being submitted and the page is refreshing because there is a button inside the form that acts as a submit button. By clicking on it, the form is being automatically submitted.

To prevent this, you can explicitly set the button type to "button" so that it does not trigger form submission immediately. Instead, you can call the onAlert() method for validation before submitting the form.

You can implement this by modifying your code as follows:

<form [formGroup]="xyzGroup">

    <button type="button" (click)="onAlert()">Submit</button>
</form>

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

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Varieties of data classifications for the information obtained from supabase

1 I'm encountering an issue while attempting to define the data types from Supabase. I received an error message stating: "type '{ id: string; title: string; capacity: number | null; start_date: Date | null; start_time: string | null; end_ ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

Despite its presence, @Input() remains undefined

Currently, I am engrossed in a project that aims to display information about movies. By utilizing @Input(), I am establishing a connection between the movie details from the parent component (movies) and the child component (movie-detail). Movies Parent ...

What is the best way to obtain the value of a nested formBuilder group?

Currently, my nested form is structured like this: this.form = this.formBuilder.group({ user: this.formBuilder.group({ id: ['', Validators.required], name: ['', Validators.required], phone: ['' ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

What is the best way to determine if the current page in Ionic 2 is being loaded from the sidemenu?

In my Ionic 2 application, there is a page that can be accessed either by clicking on a link in the sidenav or being active by default when the app is loaded. However, I want to implement an additional feature only when the page is accessed through the sid ...

What is the best way to perform a conditional check and return a customized object while working with a Promise?

I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

I am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

Issues with card flip functionality in Firefox

I designed this animation specifically for my website to create a unique effect. The animation involves translating on the Z-axis, making it appear as though the object is getting smaller, flipping to reveal the back of the card, and then translating back. ...

TS interfaces: Understanding the distinction between optional and mandatory properties

In this example, I am demonstrating TypeScript interfaces in a simple way: interface A: { id: number; email: string; } interface B extends A { login: string; password: string; } My goal is to have certain requirements when creating objects fr ...

Ways to invoke a slice reducer from a library rather than a React component

I've been working on a React application using the React Boilerplate CRA Template as my foundation. This boilerplate utilizes Redux with slices, which is great for updating state within a React component. However, I'm facing a challenge when try ...

Having trouble installing Bootstrap using the `npm i bootstrap` command? It seems like the

The npm i bootstrap command is not working when trying to install Bootstrap. Nothing is being added to the packages.json file or node_modules directory. Here are the dependencies listed in the package.json file: "dependencies": { "@angu ...

"What could be causing my React Native app to build without any issues even though the TypeScript compiler is throwing

Recently, I decided to explore TypeScript in combination with Expo. I took the time to set up linter and formatter integrations like typescript-eslint to help me catch errors while coding. Periodically, I run npx tsc to ensure my code compiles correctly an ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

Using Angular to invoke a method from a subclass

I am currently utilizing a RAD software that automatically creates Angular code for me. Each time, it generates two components: one is the "generated" component and the other is an empty component where you can add your own custom functions. In this scen ...

Error encountered: Unable to locate React Node during FaC testing with Jest and Enzyme

In my React Native app, we recently integrated TypeScript and I'm in charge of migrating the unit tests. One particular test is failing unexpectedly. The app includes a <LoginForm /> component that utilizes Formik. //... imports export inte ...