如果值存在,如何使用ngIf显示数据?

时间:2019-05-28 09:57:13

标签: angular

如果搜索到的数据不存在于数据库中,我需要显示一个错误信息以显示在页面上。 我应该使用ngIf还是有更好的方法来应用? 现在,一旦我点击了错误的数据,就什么也没有发生 products.component.html

<fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>
<h1>جستجو</h1>
<br /><br /><br /><br />
  <div class="search">
    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>
  </div>
<p>تاریخچه جستجو</p>
<span>{{name}}</span>
<br />
<br />
  <ul>
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>

    </li>
  </ul>
 <ul *ngIf="products.lenght">
      <li>{{products.name}}</li>
  </ul>

<router-outlet></router-outlet>

product.component.ts

import { ProductsService } from './../products.service';
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search-page',
  templateUrl:'./search-page.component.html',
  styleUrls: ['./search-page.component.scss']
})
export class SearchPageComponent implements OnInit {
  public products=[];
  resultSearch;
  item='';
constructor(
  private ProductsService:ProductsService,
  private _router:Router,
    ) {
      this.ProductsService.getProducts().
      subscribe(data=> {
        this.products=data
      // this.fetchProducts();
      }
        );
   }

 ngOnInit() {
  }
  fetchProducts()
  {
    this.resultSearch=this.products.filter(product => product.name.includes(this.item));
  }
  backToHome()
  {
    this._router.navigate(['/home']);
  }
  getProduct()
  {
    return this.products.filter(product => product.name.includes(this.item));
  }
  condition(){
    let condition = " not found!";
    if(!this.products.length){
      return condition;
    }
  }
}

3 个答案:

答案 0 :(得分:0)

<li *ngIf="resultSearch.length === 0">No matching results</li> 在代码末尾尝试一下。希望有帮助

答案 1 :(得分:0)

您可以尝试一下。

<ul *ngIf="resultSearch.length !== 0;else noContent">
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>
    </li>
  </ul>

<ng-template #noContent>No matching result...</ng-template>

答案 2 :(得分:0)

我这样解决了

condition(){
    let condition = " not found!";
    if(this.resultSearch && this.resultSearch.length==0){
      return condition;
    }
<ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>
    </li>
  </ul>
<p *ngIf="condition()">!not found</p>