Angular2 ngIf directive issue after initial button click

I have recently started using the Angular2 Framework, so please bear with me if I make any common mistakes. I have set up two forms in separate div tags: one for logging in and another for password reset. Below the login form, there is a link that, when clicked, hides the login form and displays the password reset form.

Similarly, under the password reset form, there is a link that, when clicked on, hides the password reset form and shows the login form.

The default visibility is set to the login form. Here is the HTML code:

<div class="login-block" *ngIf="!showResetPassword">
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit(loginForm)">
        <h1>Login</h1>
        <div>
            <label for="username"></label>
            <input type="text" placeholder="username" id="username" formControlName="username" />
        </div>
        <div>
            <label for="password"></label>
            <input type="password" placeholder="password" id="password" formControlName="password" />
        </div>
        <div>
            <button type="submit">Log In</button>
        </div>
    </form>
    <div>
        <a href="#" (click)="onTogglePasswordReset($event)">Reset Password?</a>
    </div>
</div>
<div class="login-block" *ngIf="showResetPassword">
    <form [formGroup]="resetForm" (ngSubmit)="onSubmit(resetForm)">
        <h1>Reset password</h1>
        <div>
            <label for="resetusername"></label>
            <input type="text" placeholder="username" id="resetusername" formControlName="resetusername" />
        </div>
        <div>
          <button type="submit">Continue</button>
        </div>
    </form>
    <div>
        <a href="#" (click)="onTogglePasswordReset($event)">Account Access</a>
    </div>
</div>

And here is my TypeScript function:

onTogglePasswordReset(e: Event) {
    e.preventDefault();
    this.showResetPassword = !this.showResetPassword;
    alert(this.showResetPassword);
}

My issue arises when I click on the 'Reset Password' link for the first time. The reset form shows correctly, but clicking on 'Account Access' does not display the login form again. It works once and then stops.

A strange observation is that when I initially display the Password Reset form and then click on 'Account Access,' it does show the login form. However, if I then proceed to click on the 'Reset Password' link, everything works fine, but clicking on 'Account Access' again does not bring back the login form. It works twice and then stops working altogether.

Answer №1

It seems like you may have forgotten to define your FormControls and FormGroups in your component.ts file, as you did not provide the complete code snippet. When I tested this on Plunker, I encountered an error message in the console:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});

The issue was resolved by adding the necessary FormControls.

export class FormComponent implements OnInit {

  loginForm = new FormGroup({username: new FormControl(), password: new FormControl()})
  resetForm = new FormGroup({resetusername: new FormControl()})
  showResetPassword = false;

  constructor() { 

  }

  onTogglePasswordReset () {
      this.showResetPassword = !this.showResetPassword; 
  }

}

Feel free to check out the code on Plunker and experiment with it yourself.

Answer №2

try using this one

within your design

<a (click)="toggle(false)" *ngIf="showResetPass">Reset Password</a>
<a (click)="toggle(true)" *ngIf="!showResetPass">Login to Account</a>

implemented in your element

private passwordResetVisible = false;

toggle(value) {
    this.passwordResetVisible = value;
}

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

Angular protection filter

Every time I used Angular CLI to generate a new component, it would create the component with standard parameters: @Component({ selector: 'app-test1', templateUrl: './test1.component.html', styleUrls: ['./test1.component.css ...

having difficulty deactivating matInput within angular form

I am facing an issue with a form where I need to disable one of the inputs based on a certain condition. <mat-form-field> <input matInput formControlName="domain" [disabled]="!is_staff && recipients[selectedIndex].verified"> </m ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Error in ngx-mqtt service configuration related to the chosen protocol

Currently, in my Angular 7 application, I am utilizing the ngx-mqtt package version "^6.8.3". The application operates over https, so a secure connection is also employed for the MQTT server. This snippet shows my environment configuration (environment.ts ...

Encountering a 404 error while attempting to utilize ng2-charts

I am encountering an issue while attempting to integrate ng2-charts. Despite going through numerous similar threads on GitHub and other platforms, I have yet to find a solution. The error message I am receiving is as follows: Error: (SystemJS) XHR error ( ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Angular obscured the referencing pointer

After updating Angular, I encountered issues with my code. Previously, the following code worked fine: @Component({ templateUrl: './some.component.html', styleUrls: ['./some.component.scss'] }) export class SomeComponent { ... p ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

What are some optimal techniques for implementing content-security-policy on an Angular website?

I am currently working on enhancing the security of an Angular website by implementing security headers in IIS. While most of the headers are functioning correctly without any issues, I have encountered a roadblock with the content-security-policy header. ...

Changing the type of an object's property in TypeScript on the fly

I am working on a TypeScript function that is designed to dynamically modify the property of an object. Here is the function: const updateProperty = (value: any, key: keyof Type1, obj: Type1) => { obj[key] = value; } Below is the definition of "Typ ...

Regular expression for the validation of emails using a delimiter

Can someone help me create a regex expression for emails? This is what I have so far: \S+@\S+\.\S+ I want to repeat this X times with a ; separator. Any ideas on how to achieve this? For example, the pattern should allow strings like: ...

Ways to transfer an Object from a service to a component

I'm currently working on my website and trying to implement a cart feature where users can add items. To achieve this, I have created a service that contains the cart as an object called cart. The service has functions to add items to the cart and ret ...

Finding Nested Key Paths in TypeScript for Objects and Arrays

I am in search of a unique method to create a TypeScript type that can take an object type and retrieve all the nested key paths, including properties within arrays as well. I want to exclude any default array properties such as "push" or "pop." While I ha ...

Unable to exclude specific files using VSCode's "files.exclude" feature

In my workspace settings file, the configuration for excluding certain files is as follows: { "files.exclude": { "**/*.js": { "when": "$(basename).ts" }, "app/**/*.js.map": { "when": "$(basename).ts" ...

What is the best way to perform a query in Angular using Firebase Firestore?

I am attempting to execute queries in Angular 6 using Firebase Firestore. I have this code, and I have already installed the package "npm firebase @angularfire" but it is not working: import { Component } from '@angular/core'; import { A ...

What is the process for retrieving the serial number of a hardware device in Ionic 2?

I recently encountered an issue while trying to retrieve device details. I was able to fetch the UUID of the hardware device, but unfortunately, the serial number was inaccessible. Any suggestions or insights on how to obtain the serial number would be g ...

Troubleshooting ngFor usage with Object Arrays in Angular 2

I have created an Array of Objects in my Component class as shown below : deskCategories : Array<any>; this.deskCategories = [ { catLabel : 'Tools', catIcon : 'suitcase' }, { ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

Combining Promises in Typescript to create a single Promise

Is there a way for me to return the temp_data object filled with data after using .map? Currently, it always returns undefined because I initialize temp_data as an empty object. But if I don't do this, I can't use LooseObject. Can anyone suggest ...