I'm new to angular and i have a project that already has a login with a username and password input. The password input has a button to show the password. The problem is, that when im in the password input field and i press enter, it toggles the button to show the password instead of submitting the form. How can i change that?
component.html
<div style="text-align: center" >
<form [formGroup]="form">
<br>
<mat-form-field appearance="fill">
<mat-label>Username</mat-label>
<input name="username" formControlName="username" matInput>
</mat-form-field>
<br>
<mat-form-field appearance="fill">
<mat-label>Password</mat-label>
<input name="password" formControlName="password" matInput [type]="passwordVisible ? 'text' : 'password'">
<button mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible" [attr.aria-label]="'Hide password'"
[attr.aria-pressed]="!passwordVisible">
<mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
</button>
</mat-form-field>
<br>
<button (click)="login()" mat-raised-button>Login</button>
<button (click)="navigateToRegister()" mat-raised-button color="primary" style="margin-left: 10px">Register</button>
</form>
</div>
CodePudding user response:
Default type for the button
is submit
that might be causing this issue try changing your show/hide button type
to button
something like
<button type="button" mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible" [attr.aria-label]="'Hide password'"
[attr.aria-pressed]="!passwordVisible">
<mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
</button>
CodePudding user response:
I also stumbled upon this issue recently and was able to resolve it using the approach below.
Method onClickRevealPassword
will be called if you press enter on the password input field. Such action results in an event called pointerType
which you can detect with this method and keep the password field not to reveal the plain password value. Have a look and experiment it with your component.
<mat-form-field appearance="fill">
<mat-label>Password</mat-label>
<input name="password" formControlName="password" matInput [type]="passwordVisible ? 'text' : 'password'">
<button mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible; onClickRevealPassword($event)" [attr.aria-label]="'Hide password'"
[attr.aria-pressed]="!passwordVisible">
<mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
</button>
</mat-form-field>
onClickRevealPassword(event) {
event.preventDefault();
// Prevent revealing the password when enter button is pressed.
if (event?.pointerType) {
this.passwordVisible = !this.passwordVisible;
}
}