首页 > 解决方案 > 尽管我们在父组件中更改了两次属性的值,但 ngOnChanges 没有被调用两次

问题描述

有两个组件,即 ParentComponent 和 ChildComponent。我们将一个变量从父组件绑定到子组件。根据角度文档,只要父组件中的属性值发生更改,就会调用子组件的“ngOnChanges”。现在在 ParentComponent 中,我们两次更改该变量的值,但在 ChildComponent 中,“ngOnChanges”只被调用一次。

父组件如下:

父组件.html

<p>parentcomponent works!</p>
<button (click)="onClicking()">Click here</button>
<app-childcomponent [temp]="inputfromparent"></app-childcomponent>

父组件.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parentcomponent',
  templateUrl: './parentcomponent.component.html',
  styleUrls: ['./parentcomponent.component.css']
})
export class ParentcomponentComponent implements OnInit {

  private inputfromparent = "B"
  constructor() { }

  ngOnInit() {
  }

  onClicking(){
    this.inputfromparent = "C"; //line1
    console.log("Hello");
    this.inputfromparent= "D"; //line2
  }
}

子组件如下:

子组件.ts

import { Component, OnInit, OnChanges, Input } from '@angular/core';

@Component({
  selector: 'app-childcomponent',
  templateUrl: './childcomponent.component.html',
  styleUrls: ['./childcomponent.component.css']
})
export class ChildcomponentComponent implements OnInit, OnChanges{

  @Input() private temp = "A";
  constructor() { }

  ngOnInit() {
  }

  ngOnChanges(change){
    var test = change;
    console.log(test);
    console.log(this.temp);
  }
}

在 ParentComponent.ts 文件中,每当在 ParentComponent.html 文件中定义的单击按钮上调用“onClicking”方法时,我们都会更改“inputfromparent”的值两次(请参阅第 1 行和第 2 行)。由于我们将此变量与 ChildComponent.ts 文件的变量“temp”绑定,因此 ChildComponent.ts 文件的“ngOnChanges”应该按照角度文档调用两次,如下所示:

A lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.

但是,只要在 ParentComponent.html 文件中定义的单击按钮上调用“onClicking”时,ChildComponent.ts 文件的“ngOnChanges”只会被调用一次。

我的疑问是,由于我们在 ParentComponent.ts 文件的“onClicking”方法中更改了“inputfromparent”的值两次,所以 ChildComponent.ts 文件的“ngOnChanges”应该被调用两次。但它只被调用一次。

标签: angulartypescriptngonchanges

解决方案


  onClicking() {
    this.inputfromparent = "C"; //line1
    console.log("Hello");
    this.inputfromparent= "D"; //line2
  }

这同步运行。也就是说,在onClicking结束运行之前不会执行其他代码:对于整个外部世界(模板引擎、更改检测等),onClicking()在它之前被调用,它的值inputfromparent是“B”,在它之后,它是“D” ”。两者之间几乎是一个黑匣子。


推荐阅读