我有一个第三方 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/