繁体   English   中英

Angular 4 ngfor或ngif

[英]Angular 4 ngfor or ngif

我不知道该怎么用解决我的问题。

我从HTTP请求中获取了一些信息,并且当产品具有先决条件时,我需要从该产品中显示先决条件。 如果没有它,我希望它向我显示诸如<h1>Test</h1>类的静态消息。

这是我的打字稿

  public getAllProducts() {
    return new Promise((resolve, reject) => {
      this.http
        .get(
          `${this.kioskservice.getAPIUrl()}products/?apikey=${this.kioskservice.getAPIKey()}&format=json`
        )
        .toPromise()
        .then(
          res => {
              this.config = res.json();
              // Get all product names
            if (this.config && this.config.length) {
              this.names = [];
              for (let i = 0; i < this.config.length; i++) {
                this.names.push(this.config[i]['Name']);
              }
              } 
              // Get all preruiquisites of the products
              if (this.config && this.config.length) {
                  this.prerequisites = [];
                  for (let i = 0; i < this.config.length; i++) {
                      this.prerequisites.push(this.config[i]['Prerequisites']);
                  }
              }
              console.log(this.prerequisites);
            resolve();
          },
          msg => {
            throw new Error("Couldn't get all Bookings: " + msg);
          }
        );
    });
  }
  public getNames() {
    return this.names
    }

  public getPrerequisites() {
    return this.prerequisites
    }
}

这是我的HTML

<li *ngFor="let prerequisite of productservice.getPrerequisites()">
    <i>{{prerequisite}}</i>
</li>
<li *ngFor="let prerequisite of !productservice.getPrerequisites()">
    <i>TEST</i>
</li>

上面的HTML将向我显示我从HTTP请求接收的所有40个对象,但是这40个对象中只有4个具有必备文本,因此我将获得36个空的<i>元素和4个带有必备文本的<i>元素。

UPDATE

对象数组的图像

您只需要一个*ngFor即可遍历数组,然后使用*ngIf决定要显示的内容。

<li *ngFor="let prerequisite of productservice.getPrerequisites()">
    <i *ngIf="prerequisite">{{prerequisite}}</i>
    <i *ngIf="!prerequisite">TEST</i>
</li>

暂无
暂无

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

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