0

I have an input field which gets validated on (keypress). However this is not happening. The only time it works is if I go to another input field or click away and return. This is my code for it.

  <mat-form-field>
    <input matInput placeholder="Network Address" name="network" [(ngModel)]="model.network" required (keypress)="validate($event)">
    <mat-hint>CIDR format, e.g. 192.168.65.0/25</mat-hint>
    <mat-error *ngFor="let error of errors_by_field['network']">{{error.message}}</mat-error>
  </mat-form-field>

  validate() {
    this.http.post<GetItemResult>('/api/branches', this.model).subscribe(data => {
        this.result = data;
        console.log(this.result);
        this.branch = data.item;
        this.errors_by_field = errors_by_field(data.errors);
        for (const [field, errors] of Object.entries(this.errors_by_field)) {
          if (field !== 'global') {
            this.form.form.controls[field].setErrors({server_error: true});
          }
        }
      },
      err => {
        this.submitting = false;
      });
  }

When I console log the ts code result, it prints out the result on every key press, its just not showing the on the first time the input is touched. I have to click elsewhere and return for it to work

2
  • show your .ts code as well Commented Sep 3, 2018 at 14:10
  • please see edit in question Commented Sep 3, 2018 at 14:11

2 Answers 2

1

Try with (input)="validate($event)"instead of (keypress). I think keypress is executed only when the focus switch on another element.

If it's not a reactive form, you can also use (ngModelChange).

Sign up to request clarification or add additional context in comments.

2 Comments

tried it, still does the same thing, tried (keyup/down), (ngModalChange), (input), starting to think the problem lies elsewhere with Angular material
when I console log the ts code result, it prints out the result on every key press, its just not showing the <mat-error> on the first input focus
0

Ok, so I done something like this and it worked :( <div *ngFor="let error of errors_by_field['network']"><mat-error *ngIf="error">{{error.message}}</mat-error></div>

I know material uses ErrorStateMatcher but that wont work with server side validation in my case

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.