angular - 列表未按 Angular 更新

标签 angular ionic3

我是 Angular 的新手,我有一个基本级别的问题,即当我将新对象添加到我的数组时列表没有更新。

当我点击这个按钮时,我有一个按钮,我正在向数组列表添加新对象,但列表没有更新,而且我按日期按我的数组列表分组,这是问题吗有人可以帮忙吗我请。

.ts:

export class HomePage {

  events: any;

ionViewDidLoad() {

    this.events = [
      {
        "id": 1,
        "date": "2017-12-26",
        "title": "First event"
      },
      {
        "id": 2,
        "date": "2017-12-30",
        "title": "Second event"
      },
      {
        "id": 3,
        "date": "2017-12-26",
        "title": "Third event"
      },
      {
        "id": 4,
        "date": "2017-12-31",
        "title": "Last event"
      }
    ];

  }

  add(){

     this.events.push({
      "id": 5,
      "date": "2017-12-26",
       "title": "Test event"
     });
  }
}

.html:

 <ion-content padding>

        <div *ngIf="!events || events.length === 0">
            <p>No messages</p>
        </div>

      <div *ngIf="events && events?.length > 0 ">
        <ion-item-group *ngFor="let group of events | groupByCategory: 'date'">
          <ion-item-divider color="light">
            {{ group.key }}
          </ion-item-divider>
          <ion-item *ngFor="let event of group.list">{{ event.title }}</ion-item>
        </ion-item-group>
      </div>

      <div class="bottomright" (click)="add()">Add</div>

    </ion-content>

自定义管道:

@Pipe({ name: 'groupByCategory' })
export class GroupbycategoryProvider implements PipeTransform {

  transform(value: any, groupByKey: string) {

    const events: any[] = [];
    const groupedElements: any = {};

    value.forEach((obj: any) => {
      if (!(obj[groupByKey] in groupedElements)) {
        groupedElements[obj[groupByKey]] = [];
      }
      groupedElements[obj[groupByKey]].push(obj);
    });

    for (let prop in groupedElements) {
      if (groupedElements.hasOwnProperty(prop)) {
        events.push({
          key: prop,
          list: groupedElements[prop]
        });
      }
    }
    return events;
  }
}

最佳答案

我目前无法理解这个问题,但试试这个:

 add(){

     this.events.push({
      "id": 5,
      "date": "2017-12-26",
       "title": "Test event"
     });
     this.cr.detectChanges();
  }

此外,将其添加到您的构造函数中,例如:

constructor(private cr: ChangeDetectorRef ){}

然后导入。

关于angular - 列表未按 Angular 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51281171/

相关文章:

html - Angular Material 动画 - matRipple : escapes bounds of a div element

Angular 2 : Why am I getting "Pipe not found" error?

css - 在div的特定高度显示完整图像

angular - ionic CLI 3 : ionic cordova resources - any chance to avoid login

css - ionic 卡对齐上的 Ionic 3 ionic 网格

javascript - HTTP 状态代码 401,即使我在请求中发送凭据

typescript - Angular2路由,使用TypeScript,编译报错,获取意外token Console报错

javascript - 多个模板 url Angular 6

html - 如何在 Ionic 3 中实现文本的图像叠加

angular - 在 Ionic2 应用程序中在哪里保存 API url 等设置?