直接设置属性时ngOnChanges不触发

Aym*_*ari 1 typescript angular

我使用了 ng-bootstrap 中的模态

在我的父组件中,我曾经modalService打开模态,然后使用将数据发送到模态componentInstance

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

堆栈闪电战

父组件

  public toAttach(): void {
    let modalRef = this.modalService.open(HelloComponent);
    modalRef.componentInstance.attachments = this.attachments;
  }
Run Code Online (Sandbox Code Playgroud)

模态成分

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

小智 5

当你直接设置组件实例的值时,它不会触发 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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并在父组件中调用

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