I have a third party angular component which is a table displaying the user data. If the passed object to the table changes, the table updates itself.
How does Angular detect changes to an object? I have following example:
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;
}
}
Does that mean I have to completely replace the object to trigger the change detection or am I somehow completely missing the point? Or could it be a problem with the third party library (which is Clarity Design System
)
ngDoCheck
means your component is being checked — read this article – Max Koretskyithis.users = [...this.users, user]
orthis.users = this.users.concat(user)
(both are equivalent after TS compilation) – j2L4e