Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Submit method executed by clicking another button

I'm using Angular with Angular Material components. So, I added a login component (form) where the user can type in his email and password. The input field for the password has an eye on the end to enable the user to display the password in plain text if wanted. Unfortunately, by clicking twice the eye button, the submit method executes which is binded to the submit button.

The simple question is: why?

Template

<form [formGroup]='loginForm' (ngSubmit)="onSubmit()">
<div>
    <mat-form-field>
        <mat-label for="email">E-Mail</mat-label>
        <input matInput type="text" formControlField="email" />
        <mat-error>
            Test
        </mat-error>
    </mat-form-field>
</div>

<div>
    <mat-form-field>
        <mat-label for="password">Password</mat-label>
        <input matInput [type]="hide ? 'password' : 'text'" formControlField="password" />
        <button mat-icon-button matSuffix class="mat-icon-button mat-button-base" (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
            <mat-icon>{{ hide ? 'visibility_off' : 'visibility' }}</mat-icon>
        </button>
    </mat-form-field>
</div>

<button mat-raised-button color="primary" type="submit">Login</button>

Component

export class LoginComponent implements OnInit {

loginForm: FormGroup;
hide = true;

constructor(
 private formBuilder: FormBuilder
) { 
   this.loginForm = this.formBuilder.group({
   email: ['', [Validators.required, Validators.email]],
   password: ['', [Validators.required]]
 })
}

onSubmit() {
 window.alert("Login button clicked");
}
like image 231
micu Avatar asked Dec 17 '22 14:12

micu


1 Answers

Try adding type="button" to your "eye" button.

This will tell the browser not to treat it as a submit button when inside a form.

The reason is that missing type argument from button is treated as default state and by default button element has submit.

The missing value default and invalid value default are the Submit Button state.

Source: https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type

like image 82
Kurt Hamilton Avatar answered Feb 15 '23 23:02

Kurt Hamilton