【问题标题】:Angular2+, will Event emitter trigger change detection?Angular 2,Eventemitter 会触发变化检测吗?
【发布时间】:2018-10-22 15:37:11
【问题描述】:
  • 父组件有一个子组件(child1)
  • child1 组件有一个输入属性 person 和 OnPush changeDetection 策略
  • 在子组件内部,使用 ngOnInit 中的 settimeout 来可变更改人。

    • 由于 onPush 策略,通常 dom 视图不会更新
    • 但是,如果我使用事件发射器将这个可变的更改发送到它的 父级依次更改属性绑定(可变)、视图 得到更新。

所以我的问题就在这里,事件发射器会触发视图检查吗?(更改检测)。 谢谢!

父组件

@Component({
  selector: 'app-root',
  template: '<app-child1 [person]="person", (changOnPerson)="onPersonChange($event)">',
})
export class AppComponent {
  person: Person = {
    name: 'Alex',
    age: 20
 };
 constructor() {
 }
 onPersonChange($event) {
    this.person = $event.change;
  }
}

child1.组件

@Component({
  selector: 'app-child1',
  template: '{{person | json}}',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class Child1Component implements onInit {
  @Input() person: Person;
  @Output() changOnPerson = new EventEmitter();
  constructor() { }

  ngOnInit() {
    setTimeout(() => {
      this.person.name += ' ,abc';

      // core code here !
      this.changOnPerson.emit({ change: this.person });
    }, 2000);
  }
}

【问题讨论】:

    标签: angular angular2-changedetection


    【解决方案1】:

    我认为它不会,因为 EventEmitter 是一个 Observable,因此我不认为它被包裹在 NgZone 中。

    尽管尽可能不要依赖更改检测默认值。只需使用 OnPush。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 2021-12-10
      • 2021-03-28
      • 1970-01-01
      • 2017-05-04
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多