角度对象变化检测

前端之家收集整理的这篇文章主要介绍了角度对象变化检测前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个第三方角度组件,它是一个显示用户数据的表.如果传递给表的对象发生更改,表将自行更新.

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

猜你在找的Angularjs相关文章