首页 > 解决方案 > 直接设置属性时不会触发 ngOnChanges

问题描述

我使用了 ng-bootstrap 的模态

在我的父组件中,我曾经modalService打开模式,并使用componentInstance.

在模态组件中,我用来ngOnChanges获取我发送的数据。但未ngOnChanges触发。

堆栈闪电战

父组件

  public toAttach(): void {
    let modalRef = this.modalService.open(HelloComponent);
    modalRef.componentInstance.attachments = this.attachments;
  }

模态分量

  ngOnChanges(changes: SimpleChanges) {
    console.log("start!");
    if (changes["attachments"] && changes["attachments"].currentValue) {
      console.log(changes["attachments"].currentValue);
    }
  }

标签: angulartypescript

解决方案


当您直接设置组件实例的值时,它不会触发 ngOnChanges。ngOnChanges 在组件的值绑定发生更改时触发。它还取决于更改检测策略。如果您想直接更改组件实例变量的值,可以使用 setter 方法,在该方法中您可以在 ngOnChanges 中执行您想要执行的操作。例如 -

import {
  Component,
  Input,
  AfterViewInit,
  ChangeDetectorRef,
  SimpleChanges,
  OnChanges
} from "@angular/core";

@Component({
  selector: "hello",
  templateUrl: "./hello.component.html"
})
export class HelloComponent implements AfterViewInit, OnChanges {
  @Input()
  public attachments: any[];

  constructor(private cd: ChangeDetectorRef) {}

  ngAfterViewInit() {
    this.cd.detectChanges();
  }

  setAttachments(attachments: []) {
     this.attachments = attachments.slice();
     // => DO YOUR WORK HERE
     // Like calling change detection.
   }

  ngOnChanges(changes: SimpleChanges) {
    console.log("start!");
    if (changes["attachments"] && changes["attachments"].currentValue) {
      console.log(changes["attachments"].currentValue);
    }
  }
}

在父组件中,调用

public toAttach(): void {
    let modalRef = this.modalService.open(HelloComponent);
    modalRef.componentInstance.setAttachments(this.attachments);
  }

推荐阅读