简体   繁体   English

角度对象变化检测

[英]Angular object change detection

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? Angular如何检测对象的变化? I have following example: 我有以下示例:

user.component.ts : 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 ) 或者它可能是第三方库( Clarity Design System )的问题

The table component you are using is probably implementing ChangeDetectionStrategy.OnPush . 您正在使用的表组件可能正在实现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 这是一个解释它的链接: https//angular-2-training-book.rangle.io/handout/change-detection/change_detection_strategy_onpush.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM