3
votes

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)

1
To create a new array instance you can use this.users = [...this.users, user] or this.users = this.users.concat(user) (both are equivalent after TS compilation)j2L4e

1 Answers

4
votes

The table component you are using is probably implementing ChangeDetectionStrategy.OnPush.

This means that the component will treat all input as immutable (meaning it can never change), and therefor only run change detection if the input object is replaced.

Here is a link explaining it a bit more: https://angular-2-training-book.rangle.io/handout/change-detection/change_detection_strategy_onpush.html