简体   繁体   English

为什么只有单击两次按钮才能显示垫错误?

[英]Why is my mat-error only shown if I click two times on button?

I have a search bar that retrieves data from my database, whenever the search is successful the data retrieved populates a mat table, so far so good and it works. 我有一个搜索栏,可以从数据库中检索数据,只要搜索成功,检索到的数据就会填充到一张席子表中,到目前为止效果很好,并且可以正常工作。

The problem I'm facing is when that search is unable to retrieve anything from the database because the user provided invalid information. 我面临的问题是,由于用户提供了无效信息,该搜索无法从数据库中检索任何内容。

When I provide data to the input form and the HTTP Response fails, a mat-error is supposed to trigger instantly, however that only happens if I click on the search button two times. 当我向输入表单提供数据并且HTTP响应失败时,应该立即触发mat-error,但是只有当我两次单击搜索按钮时才会发生。

This is the code I have: 这是我的代码:

MyComponent.component.ts MyComponent.component.ts

public inputForm: FormControl;

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

private searchForReturnByOrderNumber(value) {
  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;
          this.setReturns();
        } else {
          this.openDialog(orderNrData, returnOrdNrData);
        }
      }, error => {
        if (error.status === 404) {
          this.openDialog(orderNrData, []);
        }
      });
    } else {
      this.inputForm.setErrors({ 'invalid': true });
    }
  }, error => {
    this.inputForm.setErrors({ 'invalid': true });
  });
}

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

private getErrorMessage() {
  return this.inputForm.invalid ? 'Invalid Search!' : '';
}

MyComponent.component.html MyComponent.component.html

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

  <div class="col-8 search-div">

    <mat-form-field class="search-form-field" appearance="outline">
      <mat-label>Search</mat-label>

      <input matInput class="search-input" placeholder="Ex: EU030327" [formControl]="inputForm" #searchInput>
      <mat-error *ngIf="isInputInvalid()">{{ getErrorMessage() }}</mat-error>

    </mat-form-field>

    <span matSuffix>
      <button mat-flat-button class="search-btn" color="accent" [disabled]="isInputInvalid()"
        (click)="searchForReturnByOrderNumber(searchInput.value)"><i class="fa fa-search"></i></button>
    </span>

  </div>

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

If I input some invalid data (data that is not present in the database) and press my "search-btn", my mat error won't appear, only if I press the button again. 如果我输入了一些无效数据(数据库中不存在的数据)并按下“ search-btn”,则只有再次按下按钮,我的垫子错误才会出现。

I've debugged this and the code correctly enters the intended code: 我已对此进行调试,并且代码正确输入了预期的代码:

} else {
  this.inputForm.setErrors({ 'invalid': true });
}

It sets the inputForm as invalid but the mat-error won't appear until I click the button again... 它将inputForm设置为无效,但直到再次单击按钮,才会出现mat-error。

Anyone knows what might be wrong? 有人知道怎么了吗?

Thanks! 谢谢!

The condition of your *ngIf is not recalculated. *ngIf的条件不会重新计算。 I think you can replace it by something like : 我认为您可以将其替换为:

<mat-error *ngIf="inputForm?.hasError('invalid')">{{ getErrorMessage() }}</mat-error>

Also, you don't need the condition inside the getErrorMessage() method. 另外,您不需要getErrorMessage()方法中的条件。 The message will only be displayed if you have an error to start with. 仅当您遇到错误时才显示该消息。 You might have a race condition leading this method to return an empty string. 您可能有一个竞争条件,导致此方法返回一个空字符串。 Try simplifying it. 尝试简化它。

Does your mat-error have to be ngIf*? 您的错误是ngIf *吗? Can it not just use ngClass? 不仅可以使用ngClass吗?

Would it not work if you had a property of isInputInvalid, set to false intially, and if your search method returns 'invalid', then set your isInputInvalid property to true? 如果您具有isInputInvalid属性,初始设置为false,并且您的搜索方法返回“ invalid”,然后将isInputInvalid属性设置为true,这将不起作用吗?

Then you can just use ngClass: 然后,您可以使用ngClass:

<mat-error [ngClass]="{'your-class': isInputInvalid}">{{ getErrorMessage() }}</mat-error>

EDIT: 编辑:

HTML: HTML:

<mat-error [ngClass="{'show-mat-error': isInputInvalid}">{{ getErrorMessage() }}</mat-error>

TS - you need an 'isInputInvalid' property to change: TS-您需要'isInputInvalid'属性来更改:

isInputInvalid: boolean = false;

TS - you need to implement a method along these lines to change the value of 'isInputInvalid': TS-您需要按照以下方式实现方法来更改“ isInputInvalid”的值:

if (this.inputForm.hasError('invalid')) {
   this.isInputInvalid = true;
} else {
  this.isInputInvalid = false;
}

CSS: CSS:

mat-error {
display: none;
}

.show-mat-error {
display: block;
}

I would probably also do something like this in your component so that the error is hidden each time a user navigates to the page: 我可能还会在您的组件中执行以下操作,以便每次用户导航到页面时都隐藏错误:

    constructor(private router: Router) {

  router.events.subscribe((event: Event) => {

    if (event instanceof NavigationStart) {
      this.isInputInvalid = false;
    }
  });

I hope this helps! 我希望这有帮助!

I was able to fix my problem so I'll post my solution for anyone who might bump into this issue... 我能够解决我的问题,所以我会将解决方案发布给可能遇到此问题的任何人...

I created a boolean isInputInvalid and set it to true by default. 我创建了一个布尔isInputInvalid并将其默认设置为true。 Whenever I press my search 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,则将表单控件设置为无效。

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 searchForReturnByOrderNumber(value) {
  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;
          this.setReturns();
        } else {
          this.isInputInvalid = false;
          this.openDialog(orderNrData, returnOrdNrData);
        }
      }, error => {
        this.isInputInvalid = true;
      });
    } else {
      this.isInputInvalid = true;
    }
  }, error => {
    this.isInputInvalid = true;
  });

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

private getErrorMessage() {
  return this.searchForm.controls['inputForm'].invalid ? 'Invalid Search!' : '';
}

MyComponent.component.html MyComponent.component.html

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

  <div class="col-8 search-div">
    <form [formGroup]="searchForm">
      <mat-form-field class="search-form-field" appearance="outline">
        <mat-label>Search</mat-label>

        <input matInput class="search-input" placeholder="Ex: EU030327" formControlName="inputForm" #searchInput>
        <mat-error *ngIf="searchForm.controls['inputForm'].invalid">{{ getErrorMessage() }}</mat-error>

      </mat-form-field>
    </form>

    <span matSuffix>
      <button mat-flat-button class="search-btn" color="accent" [disabled]="searchForm.controls['inputForm'].invalid"
        (click)="searchForReturnByOrderNumber(searchInput.value)"><i class="fa fa-search"></i></button>
    </span>

  </div>

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

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

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