Unexpected behaviour from mat-form-field matInput, matSuffix, and reactive form

982 Views Asked by At

I am trying to figure out why the form is being submitted when toggling the visibility icon for the password input.

From login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  public loginForm: FormGroup;
  public hide: boolean = true;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.loginForm = this.fb.group({
      email: [""],
      password: [""]
    })
  }

  onSubmit() {
    console.log("Form submit event fired...");
    console.log(this.loginForm.value);
  }

}

From: login.component.html

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
        <mat-card>
            <mat-card-header>
                <mat-card-title>
                    Login
                </mat-card-title>
            </mat-card-header>
            <mat-card-content>
                <div fxLayout="column">
                    <mat-form-field appearance="outline">
                        <mat-label>Email</mat-label>
                        <input matInput placeholder="Placeholder" formControlName="email">
                    </mat-form-field>
                    <mat-form-field appearance="outline">
                        <mat-label>Password</mat-label>
                        <input matInput [type]="hide ? 'password' : 'text'" formControlName="password">
                        <button mat-icon-button matSuffix (click)="hide = !hide">
                        <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
                        </button>
                    </mat-form-field>
                </div>
            </mat-card-content>
            <mat-card-actions>
                <button mat-button (click)="onSubmit()">Login</button>
            </mat-card-actions>

        </mat-card>
    </form>

This is what the template displays when the page loads:

enter image description here

Then I click the icon on the input box and it works and switches the input type from 'password' to 'text'. enter image description here

But then if I click the icon for a second time, toggling the input type back to 'password' it seems to trigger the onSubmit() method: enter image description here

1

There are 1 best solutions below

4
kushal shah On

Your button inside the form it will consider type="submit" by default.

so you have to make it as plain button like..

 <button type="button" mat-icon-button matSuffix (click)="hide = !hide">
                        <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
                        </button>

Here I have added type='button'

hope this will help you let me know if have an issue..

Thanks