简体   繁体   中英

Why is mat-error working on MatDialog but not on normal page?

I have a normal HTML page that has an input field and a button.

The user inserts some value on the input field and the app makes an HTTP request.

If the HTTP response is okay then the user navigates to some other page, else a mat-error is displayed alerting the user that his search is invalid.

In my mat-dialog, I have the exact same scenario.

The problem I'm having is that in my normal page I have to press the button two times for my mat-error to appear, however, in my mat-dialog, the mat-error appears instantly.

The code is exactly the same though.

This is my code:

MyComponent.component.ts & MyDialog.component.ts

public inputForm: FormControl;

ngOnInit() {
  this.inputForm = new FormControl('');
}

private getData(value: any, returnType: string) {
  if (value === undefined || value === "") {
    this.inputForm.setErrors({ 'invalid': true });
  } else {
    this.getOrder(value, returnType);
  }
}

private getOrder(value: any, returnType: string) {
  if (value.length > 0 && !isNaN(value)) {
    this.getOrderByID(value, returnType);
  } else if (value.length > 0 && isNaN(value)) {
    this.getOrderByNumber(value, returnType);
  }
}

private getOrderByID(value: number, returnType: string) {
  this.rest.getOrder(value).subscribe((orderIdData: {}) => {
    if (Object.entries(orderIdData).length !== 0) {
      this.rest.getReturnByOrderId(value).subscribe((returnOrdIdData: Return[]) => {
        if (Object.entries(returnOrdIdData).length !== 0) {
      this.returns = returnOrdIdData;
    } else {
      this.returns = [];
    }
    this.onCreateReturn(orderIdData, returnType);
      }, error => {
    if (error.status === 404) {
      this.returns = [];
    }
    this.onCreateReturn(orderIdData, returnType);
      });
    } else {
      this.inputForm.setErrors({ 'invalid': true });
    }
  }, error => {
    this.inputForm.setErrors({ 'invalid': true });
  });
}

private getOrderByNumber(value: string, returnType: string) {
  this.rest.getOrderByNumber(value).subscribe((orderNrData: {}) => {
    if (Object.entries(orderNrData).length !== 0) {
      this.rest.getReturnByOrderNumber(value).subscribe((returnOrdNrData: Return[]) => {
        if (Object.entries(returnOrdNrData).length !== 0) {
      this.returns = returnOrdNrData;
    } else {
      this.returns = [];
    }
    this.onCreateReturn(orderNrData, returnType);
      }, error => {
    if (error.status === 404) {
      this.returns = [];
    }
    this.onCreateReturn(orderNrData, returnType);
      });
    } else {
      this.inputForm.setErrors({ 'invalid': true });
    }
  }, error => {
    this.inputForm.setErrors({ 'invalid': true });
  });
}

private getErrorMessage() {
  return (<HTMLInputElement>document.getElementById("input-form-id")).value === "" ? 'Este campo é obrigatório!' : 'A encomenda que inseriu não existe!';
}

private onCreateReturn(el: {}, returnType: string) {
  this.setData(el, returnType);
  this.router.navigate(['returns-create']);
}

private isInputInvalid() {
  if (this.inputForm.invalid) return true;
    return false;
}

MyComponent.component.html & MyDialog.component.html

<div class="row">
  <div class="col-2 order-label">Order: </div>

  <div class="col-8 search-div">
    <mat-form-field class="search-form-field" appearance="standard">
      <input matInput class="order-input" id="input-form-id" placeholder="Ex: EU030327" [formControl]="inputForm" #searchInput>
      <mat-error *ngIf="isInputInvalid()">{{ getErrorMessage() }}</mat-error>
      <mat-hint>Insira o ID ou o Nº de uma encomenda.</mat-hint>
    </mat-form-field>
  </div>

  <div class="col-2"></div>
</div>

<br>

<button mat-raised-button color="accent" (click)="getData(searchInput.value, 'Refund')" [disabled]="isInputInvalid()">Refund</button>

I need the mat-error to appear when the response returns an error or the response is empty, however that is only the case in MyDialog component...

Why is this happening?

Thanks!

For anyone who might bump into this issue after a few days of trial and error, I achieved a working solution...

I created a boolean isInputInvalid and set it to true by default. Whenever I press my button, the HTTP request is executed and, depending on the response, the isInputInvalid boolean is set to true or false. If the HTTP response is invalid I set it to true, if it's valid I set it to false.

Then, if the boolean is true, I set my Form Control as invalid.

In my HTML file I surrounded my input with a <form> and created a [formGroup] . For error validation I set the *ngIf inside <mat-error> equal to searchForm.controls['inputForm'].invalid .

Here is my code:

MyComponent.component.ts

private searchForm: FormGroup;
private isInputInvalid: boolean = true;

ngOnInit() {
  this.searchForm = new FormGroup({
    inputForm: new FormControl('')
  });
}

private getData(value: any, returnType: string) {
  if (value === undefined || value === "") {
    this.inputForm.setErrors({ 'invalid': true });
  } else {
    this.getOrder(value, returnType);
  }
}

private getOrder(value: any, returnType: string) {
  if (value.length > 0 && !isNaN(value)) {
    this.getOrderByID(value, returnType);
  } else if (value.length > 0 && isNaN(value)) {
    this.getOrderByNumber(value, returnType);
  }
}

private getOrderByID(value: number, returnType: string) {
  this.rest.getOrder(value).subscribe((orderIdData: {}) => {
    if (Object.entries(orderIdData).length !== 0) {
      this.rest.getReturnByOrderId(value).subscribe((returnOrdIdData: Return[]) => {
        if (Object.entries(returnOrdIdData).length !== 0) {
          this.isInputInvalid = false;
          this.returns = returnOrdIdData;
        } else {
          this.isInputInvalid = false;
          this.returns = [];
        }
        this.onCreateReturn(orderIdData, returnType);
      }, error => {
        this.isInputInvalid = true;
        if (error.status === 404) {
          this.returns = [];
        }
        this.onCreateReturn(orderIdData, returnType);
      });
    } else {
      this.isInputInvalid = true;
    }
  }, error => {
    this.isInputInvalid = true;
  });

  if(this.isInputInvalid){
    this.searchForm.controls['inputForm'].setErrors({ 'invalid': true });
  }
}

private getOrderByNumber(value: string, returnType: string) {
  this.rest.getOrderByNumber(value).subscribe((orderNrData: {}) => {
    if (Object.entries(orderNrData).length !== 0) {
      this.rest.getReturnByOrderNumber(value).subscribe((returnOrdNrData: Return[]) => {
        if (Object.entries(returnOrdNrData).length !== 0) {
          this.isInputInvalid = false;
          this.returns = returnOrdNrData;
        } else {
          this.isInputInvalid = false;
          this.returns = [];
        }
        this.onCreateReturn(orderNrData, returnType);
      }, error => {
        this.isInputInvalid = true;
        if (error.status === 404) {
          this.returns = [];
        }
        this.onCreateReturn(orderNrData, returnType);
      });
    } else {
      this.isInputInvalid = true;
    }
  }, error => {
    this.isInputInvalid = true;
  });

  if(this.isInputInvalid){
    this.searchForm.controls['inputForm'].setErrors({ 'invalid': true });
  }
}

private getErrorMessage() {
  return (<HTMLInputElement>document.getElementById("input-form-id")).value === "" ? 'Este campo é obrigatório!' : 'A encomenda que inseriu não existe!';
}

private onCreateReturn(el: {}, returnType: string) {
  this.setData(el, returnType);
  this.router.navigate(['returns-create']);
}

MyComponent.component.html

<div class="row">
  <div class="col-2 order-label">Order: </div>

  <div class="col-8 search-div">
    <form [formGroup]="searchForm">
      <mat-form-field class="search-form-field" appearance="standard">
        <input matInput class="order-input" id="input-form-id" placeholder="Ex: EU030327" formControlName="inputForm" #searchInput>
        <mat-error *ngIf="searchForm.controls['inputForm'].invalid">{{ getErrorMessage() }}</mat-error>
        <mat-hint>Insira o ID ou o Nº de uma encomenda.</mat-hint>
      </mat-form-field>
    </form>
  </div>

  <div class="col-2"></div>
</div>

<br>

<button mat-raised-button color="accent" (click)="getData(searchInput.value, 'Refund')" [disabled]="searchForm.controls['inputForm'].invalid">Refund</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM