简体   繁体   English

为什么mat-error在MatDialog上工作但在普通页面上没有?

[英]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. 我有一个普通的HTML页面,它有一个输入字段和一个按钮。

The user inserts some value on the input field and the app makes an HTTP request. 用户在输入字段上插入一些值,应用程序发出HTTP请求。

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. 如果HTTP响应正常,则用户导航到其他页面,否则显示mat-error警告用户他的搜索无效。

In my mat-dialog, I have the exact same scenario. 在我的mat对话框中,我有完全相同的场景。

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. 我遇到的问题是,在我的正常页面中,我必须按两次按钮才能显示mat-error,但是,在我的mat-dialog中,mat-error会立即出现。

The code is exactly the same though. 但代码完全相同。

This is my code: 这是我的代码:

MyComponent.component.ts & MyDialog.component.ts MyComponent.component.tsMyDialog.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 MyComponent.component.htmlMyDialog.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... 我需要在响应返回错误或响应为空时出现mat-error,但这只是MyDialog组件中的情况......

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. 我创建了一个布尔值isInputInvalid并默认将其设置为true。 Whenever I press my button, the HTTP request is executed and, depending on the response, the isInputInvalid boolean is set to true or false. 每当我按下我的按钮时,都会执行HTTP请求,并且根据响应, isInputInvalid布尔值设置为true或false。 If the HTTP response is invalid I set it to true, if it's valid I set it to false. 如果HTTP响应无效,我将其设置为true,如果它有效,我将其设置为false。

Then, if the boolean is true, I set my Form Control as invalid. 然后,如果布尔值为true,我将Form Control设置为无效。

In my HTML file I surrounded my input with a <form> and created a [formGroup] . 在我的HTML文件中,我用<form>包围了我的输入并创建了[formGroup] For error validation I set the *ngIf inside <mat-error> equal to searchForm.controls['inputForm'].invalid . 对于错误验证,我将<mat-error>*ngIf设置为等于searchForm.controls['inputForm'].invalid

Here is my code: 这是我的代码:

MyComponent.component.ts 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular2 / 4材料设计, <mat-error> 不工作 - 没有找到结果 - Angular2/4 material-design, <mat-error> not working - when no results found 为什么只有单击两次按钮才能显示垫错误? - Why is my mat-error only shown if I click two times on button? 角度材料mat-error无法显示消息 - Angular material mat-error cannot show message NullInjectorError:没有 MatDialog 的提供者! 使用带有垫子对话框的防护时显示错误 - NullInjectorError: No provider for MatDialog! error showing while using guard with mat dialog Mat-Error 首次打开表单时显示所需的验证错误消息 - Mat-Error Required validation error message shows when form is first open Angular Material Mat-error 显示有效输入错误,同时使用正则表达式验证 - Angular Material Mat-error Showing error for valid inputs, while validating with regex 当 http get 请求状态返回 404 时显示 Angular Material mat-error - Display Angular Material mat-error when http get request status returns 404 Angular CanDeactivate Guard not working with MatDialog - Angular CanDeactivate Guard Not Working Properly With MatDialog 为什么 EventEmitter 在 mat-menu 上不起作用(触发)? - Why EventEmitter not working (firing) on mat-menu? MatDialog 服务单元测试 Angular 6 错误 - MatDialog Service Unit Test Angular 6 Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM