gpt4 book ai didi

Angular 对象变化检测

转载 作者:太空狗 更新时间:2023-10-29 17:49:50 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com