首页 > 解决方案 > Angular 6检测对象数组内部变化的方法?

问题描述

如果没有检测到更改,我有一个保存按钮需要禁用。我实现了自己的变更检测,但我觉得 Angular 6 必须存在一些东西?我尝试使用 DefaultKeyValueDiffer 和 IterableDiffer 但无法弄清楚如何正确使用它们。使用其中任何一种方法是否正确?下面发布的是我当前的自定义解决方案:

import { Component, OnInit, ViewChild } from '@angular/core';
import { TagService } from '../../services/tag.service';
import { AuthService } from '../../services/auth.service';

import { Tag } from '../../models/tag';
import { Company } from '../../models/company';
import { TagColumnDetail } from '../../models/tag-column-detail';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  initialTagState: Tag[];
  tags: Tag[];
  updatedTags: Tag[];

  constructor(
    private tagService: TagService
   ) {}

  @ViewChild(TableComponent) table:TableComponent;

  ngOnInit() {  this.authService.getActiveCompany$().subscribe((company: Company) => {
      this.activeCompany = company;
      if (this.activeCompany) {
        Promise.all([
          this.tagService.getColumns(),
          this.tagService.getTags(this.activeCompany.Id)
        ]).then(([tagCols, tags]) => {
          this.tagCols = tagCols;
          this.setTags(tags, true);
          this.initialTagState = JSON.parse(JSON.stringify(this.tags));
        });
      }
    });
  }

  setTags(tags, init=false) {
    this.tags = tags
    if(!init) {
      this.changesMadeToPolicy()
    }
  }

  changesMadeToPolicy() {
    let changes = this._getChanges(this.initialTagState, this.tags)
    this.updatedTags = changes
  }

  _getChanges(oldArray, newArray) {
    let changes, i, item, j, len;
    if (JSON.stringify(oldArray) === JSON.stringify(newArray)) {
      return false;
    }
    changes = [];
    for (i = j = 0, len = newArray.length; j < len; i = ++j) {
      item = newArray[i];
      if (JSON.stringify(item) !== JSON.stringify(oldArray[i])) {
        changes.push(item);
      }
    }
    return changes;
  };

}

标签: angular

解决方案


推荐阅读