Utilize the error message as a label following the submission of the form

I need to implement a password reset form for user authentication purposes. Below is the HTML code:

<form class="grid-wrapper" #f="ngForm" *ngIf="stepOne">

  <div class="form-group first-row">
    <label for="name">Username</label>
    <input id="name" type="text" name="name" class="form-control" required [(ngModel)]="user.name">
  </div>

  <div class="form-group second-row">
    <label for="email">Email</label>
    <input id="email" type="text"
           name="email"
           class="form-control"
           email required
           [(ngModel)]="user.email"
           [ngClass]="{ 'is-invalid': nameEmailMismatch || notFound }">
    <div class="invalid-feedback-custom">
      <div *ngIf="nameEmailMismatch">Provided email doesn't belong to current user</div>
      <div *ngIf="notFound">User not found</div>
    </div>
  </div>

  <div class="btn-row third-row">
    <button class="btn btn-primary" [disabled]="f.invalid || loading" (click)="submit()">Reset</button>
  </div>

</form>

<div *ngIf="stepTwo">

  <div>
    <h2>Password reset link has been sent to your email</h2>
  </div>

</div>

<div class="complete" *ngIf="stepFour">
  <p>
    Your password has been reset
  </p>
  <a class="btn btn-primary" routerLink="/login">Login</a>
</div>

For the component part, here is an example:

@Component({
  ........
})
export class ResetPasswordNewComponent implements OnInit {

  user: UserReset = new UserReset(null, null, null, null, null, null);

  stepOne = true;
  stepTwo = false;

  loading = false;

  nameEmailMismatch = false;
  notFound = false;

  constructor(private resetService: PasswordResetService,
              private route: ActivatedRoute) {
  }

  ngOnInit() {
  }

  submit() {
    this.loading = true;
    this.nameEmailMismatch = false;
    this.notFound = false;

    this.resetService.requestReset(this.user).subscribe(user => {
        this.stepOne = false;
        this.stepTwo = true;
        this.loading = false;
      },
      error => this.handleError(error));
  }

  handleError(error) {
    console.log(error);
    this.loading = false;
    switch (error.error) {
      case 'NAME_AND_EMAIL_MISMATCH':
        this.nameEmailMismatch = true;
        break;
    }

    switch (error.status) {
      case 404:
        this.notFound = true;
        break;
    }

  }
}

If you are looking for another solution to display messages after form submission when user or password is not found, consider using label elements that can be toggled based on certain conditions, rather than relying solely on setting variables to true and false.

Answer №1

One option is to utilize the reactiveform for form validation, which allows you to use the function

setError('custom-error', true/false)
. This can be implemented in your form submission process. Feel free to reach out if you require further clarification.

Answer №2

You can check the submitted property of the ngForm to determine if the form has already been submitted.


  <div class="invalid-feedback-custom" *ngIf="f.submitted"> <!-- Validate form submission -->
      <div *ngIf="nameEmailMismatch">The provided email does not match the current user</div>
      <div *ngIf="notFound">User not found</div>
    </div>

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

Arrange text and a button side by side in a table cell using an Angular directive and an HTML template

I have successfully implemented an Angular search function on my project. You can find it here to allow users to search for courses. The search function uses a read-more directive that displays a preview of the description and keywords before allowing use ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

How come Typescript allows me to generate intersection types that seem impossible?

Despite being unimplementable, the type definition below does not trigger any warnings from the compiler. // No type error type impossible = 0 & string[] & 'anything' An item cannot simultaneously be a number, a string[], and a stri ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

The module 'AppModule' is throwing an error due to the unexpected value 'Validators' being imported. Make sure to include a @NgModule annotation to resolve this issue

Currently, I have integrated Angular reactive forms into my application. Here is an excerpt from my app.module.ts file: import { HttpModule } from '@angular/http'; import { environment } from './../environments/environment'; import { ...

Oversee various interactions for the user

I am currently utilizing NodeJs, ExpressJs, and Angular 6 for my application, but I have encountered an issue. Within my system, there is a user with the attributes: User U: { name; email; password; } Let's assume this user, named U, is ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

"Enhancing Your Web Pages: Generating and Inserting HTML Elements on the Fly Using

For my master's degree project, I am working on developing a shopping web app. The issue I am facing is that I need assistance with creating a div and adding it to the HTML file with an ID matching the category name from the .ts file when the addCate ...

Displaying a default input placeholder in Kendo UI Datepicker for Angular 2

I've recently implemented the [Datepicker feature from Telerik Kendo UI][1] While the datepicker functions perfectly, I have encountered a single issue where it displays undefined when the date value is not defined: [![enter image description here][ ...

The pagination feature in AG-Grid causes the getRows function to be executed twice

I have a project in Angular utilizing the AG-Grid free version to showcase data. With server-side pagination not being an option in the free edition, I have implemented the infinite row model with pagination instead. Below is a demo featuring a mock servi ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

A single click is required for Observables to load on an HTML page

While working on my Angular web application, I encountered an issue with displaying data when using Observables and Subjects. Typically, when searching the Firebase DB, I use *ngFor="let myvar of _myvar | async" in my HTML to display the retrieve ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Exporting the value of a module

I'm really puzzled. Here's the javascript file that's causing confusion: module.exports = { connection: 'freshairMysqlServer', tableName: 'Accounts', autoCreatedAt: false, autoUpdatedAt: false, autoPK: false, ...

Tips for fixing the issue: How to handle the notification that an error event has already been emitted on the socket?

I'm currently developing my first Angular app by following the instructions provided at this link. However, upon running the app, I encountered the following errors: (node:4064) Warning: An error event has already been emitted on the socket. Please ...