首页 > 解决方案 > Angular 6 *ngFor 不更新视图

问题描述

我正在使用材料卡使用 *ngFor 进行填充,但它没有显示绑定

它在 DOM 中显示了这一点,但是当我控制台绑定变量时,它显示了值,但我的 mat-card 仍然没有重新填充。

注意:--当我单击任何表单字段框时,它会更改<!--bindings={ "ng-reflect-ng-for-of": "[object Object],[object Object" }-->为此并且数据开始显示

下面是我的代码

<mat-card class="inner-list-card" *ngFor="let uglist of userGroupViewModel.UserGroupList"
        (click)="getDetails(uglist['groupId'],$event)" routerLink="scope">
        <div class="inner-card">
          <li class="pointer">
            <span class="listIcon">
              <i class="fa fa-users"></i>
            </span>
            <a class="textwrap">
              {{ uglist.groupName }}
              <small class="listDate">Last Updated: {{ uglist.updatedOn*1000 | date }}</small>
            </a>
            <span>
              <a class="protected">
                <img alt="" src="assets/protected.png" height="25px" width="23px">
              </a>
            </span>
          </li>
        </div>
        <div class="desc"> {{ uglist.description }}</div>
        <div class="routing-element">Show
          More
          <i class="fa fa-angle-right alignRight" aria-hidden="true"></i>
        </div>
      </mat-card>

我浏览了以下参考链接:

angular2 ngFor 在 ngOnInit() 上从 api 获取数据时不工作

标签: angular6angular-material-6

解决方案


欢迎来到异步编程 :)

你没有包括你如何从你的 api 获取数据的细节......我所做的就是使用我订阅的 observable。一旦数据可用,就会*ngFor为我们呈现结果。

相关service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class MyService {
  apiURL: string = 'https://ddxhruyrrj.execute-api.us-east-2.amazonaws.com/aiProd/projectslazy';
  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get(this.apiURL);
  }

}

相关component.ts

export class CardFancyExample {
  dataSet:any;

  constructor(private serv: MyService) {
    this.serv.getData().subscribe(
      dataa => { console.log(dataa); this.dataSet = dataa; }
      , errr => { console.log(errr); }
    )
  }
}

相关的html

<div *ngIf="dataSet== ''">
    No data loaded
</div>
<div *ngIf="dataSet != ''">
    <mat-card class="example-card" *ngFor="let data of dataSet">
        <mat-card-header>
            <mat-card-title>{{data?.project}}</mat-card-title>
            <mat-card-subtitle>{{data?.role}}</mat-card-subtitle>
        </mat-card-header>
        <img mat-card-image src="https://www.akberiqbal.com/JumboMob.jpg" alt="Akber Iqbal">
  <mat-card-content>
    <p>
{{data?.description}}
    </p>
  </mat-card-content>
  <mat-card-actions>
    <button mat-button>LIKE</button>
    <button mat-button>SHARE</button>
  </mat-card-actions>
</mat-card>
</div>

在这里完成工作堆栈闪电战


推荐阅读