Angular 对象变化检测

标签 angular typescript

我有一个第三方 Angular 组件,它是一个显示用户数据的表格。如果传递给表格的对象发生变化,表格会自行更新。

Angular 如何检测对象的变化?我有以下示例:

user.component.ts:

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
})
export class UserComponent implements OnInit {

  private _users: User[];
  set users(users: User[]) {
    this._users = users;
  }

  get users(): User[] {
    return this._users;
  }

  constructor() {}

  addUserToTheList(user: User) {

    // this won't be detected as a change to the object
    this.users.push(user);

    // on the other hand, this will
    let userList: User[] = this.users;
    userList.push(user);
    this.users = userList;

  }
}

这是否意味着我必须完全替换对象才能触发变化检测,或者我不知何故完全忽略了这一点?或者可能是第三方库(Clarity Design System)的问题

最佳答案

您正在使用的表格组件可能正在实现 ChangeDetectionStrategy.OnPush

这意味着该组件会将所有输入视为不可变(意味着它永远不会改变),因此只有在输入对象被替换时才运行变化检测

这里有一个链接对其进行了更多解释:https://angular-2-training-book.rangle.io/handout/change-detection/change_detection_strategy_onpush.html

关于 Angular 对象变化检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812221/

相关文章:

c# - 检查 List<T> 的项目是否有效

mongodb - 使用 Typescript 在 Mongoose 中缺少子文档方法

angular - 添加@angular/fire 到 angular 12

html - Angular 结合 2 个输出事件来调用 1 个函数

typescript - 如何从响应中获取 'console.log' 数据

reactjs - 使用 React、Redux 和 TypeScript 映射 DispatchToProps 的更短方法?

typescript - 如何创建一个 Jupyter Lab 扩展,在 Jupyter Lab 笔记本的工具栏上添加一个自定义按钮?

javascript - ionic 2 : unit test for component with ionic's markup/elements

angular - 箭头运算符 VS 在函数中传递参数 : what is the difference?

angular - RxJs - 如何使用 takeuntil 运算符返回通知程序值