Home > other >  Button values does not respect input maxlenght (Point of sale/Angular)
Button values does not respect input maxlenght (Point of sale/Angular)

Time:03-28

Im having a problem with my Point of Sale app, when I fill the input with my keyboard it accepts the maxLenght but when I fill it with the values that each button has it doesnt respect. Does anyone knows something about this?

<div mat-dialog-content>
<mat-form-field appearance="fill">
    <mat-label>Password</mat-label>
    <input matInput #input [(ngModel)]="data.password" maxlength="4" type="password">
</mat-form-field>
<div >
<div >
    <button (click)="addNumber(1)">1</button>
    <button (click)="addNumber(2)">2</button>
    <button (click)="addNumber(3)">3</button>
</div>
<div >
    <button (click)="addNumber(4)">4</button>
    <button (click)="addNumber(5)">5</button>
    <button (click)="addNumber(6)">6</button>
</div>
<div >
    <button (click)="addNumber(7)">7</button>
    <button (click)="addNumber(8)">8</button>
    <button (click)="addNumber(9)">9</button>
</div>
<div >
    <button id="noBorder" (click)="reset()">Clear</button>
    <button id="noBorder" (click)="addNumber(0)">0</button>
    <button id="noBorder" (click)="delete()">Del</button>
</div>
<div mat-dialog-actions>
<button  mat-button (click)="onNoClick()">Back</button>
<button  id="ok" mat-button [mat-dialog-close]="data.password" cdkFocusInitial>Ok</button>

}

CodePudding user response:

maxLength attribute does not work programatically. Which means that it only works if the user enters something, not if JS forces it, like you do with all the buttons. Especially because doing data.password = "x" have nothing to do with the input (you only bind values with ngModel)

There is 2 way of fixing it

First: the easy one

Assuming that your add number function adds a number to the password, you check if the length is below max and add if it is

public maxLength: number = 4;

addNumber(nbr: number) {
    if (data.password.length < maxLength) {
        data.password  = `${nbr}`
    }
}

Second: the right one

What you're trying to achieve here is called programatical form validation. Angular have a very special way to achieve it. See the docs on Reactive forms. You will bind password to a form or a control, and put validators that check the length even if the value change in TS.

In component TS:

passwordControl = new FormControl("", Validators.maxLength(this.maxLength))

addNumber(nbr: number) {
    this.passwordControl.setValue(this.this.passwordControl.value   `${nbr}`)
}

In html

<mat-form-field appearance="fill">
    <mat-label>Password</mat-label>
    <input matInput #input [formControl]="passwordControl" type="password">
    <mat-error *ngIf="passwordControl.invalid">Password not matching format</mat-error>
</mat-form-field>

You can easily check if password match format and submit the form by using this.passwordControl.invalid

  • Related