Angular 角目标变化检测
我有一个第三方角度组件,它是一个显示用户数据的表。如果传递给表的对象发生更改,表将更新自身 如何检测对象的角度变化?我有以下例子:Angular 角目标变化检测,angular,typescript,Angular,Typescript,我有一个第三方角度组件,它是一个显示用户数据的表。如果传递给表的对象发生更改,表将更新自身 如何检测对象的角度变化?我有以下例子: user.component.ts: @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'], }) export class UserComponent implements OnInit {
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
这意味着该组件将把所有输入视为不可变的(这意味着它永远不会更改),因此只有在输入对象被替换时才运行更改检测
这里有一个链接对此进行了详细解释:您可以阅读此链接来创建一个新的数组实例,您可以使用
this.users=[…this.users,user]
或this.users=this.users.concat(user)
(在TS编译后两者都是等效的)