angular - 尽管我们在父组件中更改了两次属性的值,但 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”应该被调用两次。但它只被调用一次。
解决方案
onClicking() {
this.inputfromparent = "C"; //line1
console.log("Hello");
this.inputfromparent= "D"; //line2
}
这同步运行。也就是说,在onClicking
结束运行之前不会执行其他代码:对于整个外部世界(模板引擎、更改检测等),onClicking()
在它之前被调用,它的值inputfromparent
是“B”,在它之后,它是“D” ”。两者之间几乎是一个黑匣子。
推荐阅读
- javascript - 我在 Zapier 的 Action 响应中得到一个 NULL 对象。这导致操作失败并导致 Zapier 不更新身份验证令牌
- python - 在url中添加参数
- wordpress - Wordpress iFrame 中的 Acumatica 屏幕
- python - Do I need to import Numpy to use Pandas?
- python - 如何使用 pip asciimatics 在 TUI 中显示“Hello world”
- javascript - 有没有办法在 JS 中获取所有已注册的协议处理程序?
- relative-path - 如何引用 Docusaurus docs 目录之外的文档?
- powershell - 如何在 Powershell 中使用 Get-Date 的 .AddMonths 方法
- angular - Angular:以模块化方式在另一个组件之前添加一个组件
- c# - ASP.NET Core 获得部分经过身份验证的用户(即正确的用户名 + 密码,但尚未 2FA)