【问题标题】:Hide error message if the array has elements in angular4如果数组在 angular4 中有元素,则隐藏错误消息
【发布时间】:2018-10-27 16:56:10
【问题描述】:

如果没有找到数据,我想显示一条消息。我已经为此编写了逻辑并且它有效。但是,当有 一些数据时,它也会显示消息。我不知道为什么它不能正常工作。任何帮助将不胜感激。

我的打字稿组件中的逻辑

validation: boolean; 
employees = [];
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;        
        }
    });
}

这是 HTML 文件:

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

【问题讨论】:

  • 你试过这个*ngIf="validation==true"。有用吗???
  • 是的,它不工作。
  • 试试*ngIf="employees.length === 0"。
  • 第一次加载页面时有效,之后点击无效。
  • 你昨天已经问过同样的问题Unable to hide error msg in angular 4

标签: angular validation angular4-forms


【解决方案1】:

您可能有一种方法可以在您的组件中如下所示

canShowErrors() {
    return (this.employees == null || this.employees.length === 0);
}

从 HTML 你应该调用

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

【讨论】:

    【解决方案2】:

    您不应该在每次搜索时都订阅您的 http observable,这样会造成内存泄漏,请参阅:http://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

    试试:

    employees = Observable<any[]>;
    constructor( ) {
    }
    
    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.employees = this.httpClient.post<Employee[]>('sercvicesUrl', body, config)
    }
    

    在你的 HTML 中:

    <button (click)="searchEmployee(searchBox.value);">Search</button>
     <div *ngIf="!(employees | async)?.length">
    <h4>Sorry, No results</h4>
    </div>
    

    并显示它们:

    <div *ngFor="let e of employees | async">
        ...
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多