Unable to hide error msg in angular 4

邮差的信 提交于 2019-12-24 08:48:50

问题


If there is no data i want to show some message. I have written the logic for that and it works. But if there is some data then also its showing the same message. No idea why its not working properly. Help will be much appreciated.

Logic in my typescript component

  validation: boolean; 

  constructor( ) {
    this.validation = false;
  }
searchEmployee(name: string): void {
    var config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    const empName = name;
    let obj = { empNamewers: empName }
    let body = JSON.stringify(obj);
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type','application/json');
     this.httpClient.post<Employee[]>('sercvicesUrl', body, config).subscribe( employees => {
        this.employees = employees;
         console.log(employees);
      if(this.employees.length === 0){
       this.validation=true;
        }
     else{
       this.validation=false;        
    }
    });

    }

this is HTML file

     <button (click)="searchEmployee(searchBox.value);">Search</button>
     <div *ngIf="validation">
    <h4>Sorry, No results</h4>
    </div>

回答1:


There are few issues with your code. First, you should not assign class variables inside your constructor. That is not what constructors are for. If you assign it like this:

validation = false;

constructor() {}

Then, it will be assigned before angular lifecyles.

Secondly, in your check:

if(this.employees.length === 0 || this.employees.length === null){

This is incorrect. Length cannot be null; It should be:

if (!this.employees || this.employees.length === 0) {

}

Here is a working example of what you are trying to achieve:

https://stackblitz.com/edit/angular-ypaaea?file=src%2Fapp%2Fapp.component.ts




回答2:


Can you try using below code :

if(this.employees.length > 0){
    //Write you logic here
         this.validation=false;
 }
    else{
          this.validation=true;        
}

Always make sure that you return empty array ('[]') as API Response even you have do not have any matching data.



来源:https://stackoverflow.com/questions/50373058/unable-to-hide-error-msg-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!