Home > Blockchain >  Toggle show/hide password angular
Toggle show/hide password angular

Time:10-21

I have an angular application that has a login screen. I want to allow the user to toggle the password from being concealed to seeing the text by clicking on an eye in the input box. I am trying to use the mat-icon-button found here https://material.angular.io/components/form-field/overview.

It works as it shows in the link, my problem though, is that the button is being triggered when a user hits enter and I want the user to be able to hit enter to activate the login button. I have cdkFocusInitial on the login button but that doesn't seem to make a difference.

<mat-card-content>
    <form>
      <p>
        <mat-form-field>
          <input
            type="text"
            matInput
            placeholder="Username"
            [formControl]="username"
            [errorStateMatcher]="matcherusername"
          />
          <mat-error *ngIf="username.hasError('required')"> Username is <strong>required</strong> </mat-error>
        </mat-form-field>
      </p>

      <p>
        <mat-form-field>
          <input
            type="password"
            matInput
            [type]="hide ? 'password' : 'text'"
            placeholder="Password"
            [formControl]="password"
            [errorStateMatcher]="matcherpassword"
          />
          <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide Password'" [attr.aria-pressed]="hide">
            <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
          </button>
          <mat-error *ngIf="password.hasError('required')"> Password is <strong>required</strong> </mat-error>
        </mat-form-field>
      </p>

      <p *ngIf="error" >
        {{ error }}
      </p>

      <div >
        <button type="submit" [disabled]="password.hasError('required')" mat-flat-button color="primary" (click)="submit()" matTooltip="Login" cdkFocusInitial>Login</button>
      </div>

      <div class ="forgot username">
        <nav>
          <a routerLink = "/login/forget-username"><small>Forgot Username?</small></a>
        </nav>
        <router-outlet></router-outlet>
      </div>

      <div class ="forgot password">
        <nav>
          <a routerLink = "/login/forget-password"><small>Forgot Password?</small></a>
        </nav>
        <router-outlet></router-outlet>
      </div>
    </form>
  </mat-card-content>

I know I can move the logic to the .ts file and do it that way, but I'm wondering if it's possible to resolve this without involving extra code in the .ts file.

CodePudding user response:

You just need to add a button type to the button, if you don't define the type of the button it will act as a submit button, should look like the following code:

<button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide Password'" [attr.aria-pressed]="hide" type="button"></button>

  • Related