gpt4 book ai didi

javascript - 为什么 Angular 组件的实例化顺序与 if 条件不符合预期?

转载 作者:行者123 更新时间:2023-12-04 07:21:06 24 4
gpt4 key购买 nike

我在文档中找不到任何地方,为什么 Angular 组件的实例化顺序与 不符合预期顺序如果 健康)状况?我期待它的顺序与它们在控制台中写入的顺序相同。即 1 2 3 4 5(在 HTML 方面是正确的)
但它来了 3 4 5 1 2
虽然我在观察到 的这种行为后做出了假设如果 条件延迟执行与没有它相比,但找不到它的原因/文档。
Slackblitz 链接以验证此行为:
https://stackblitz.com/edit/angular-looping-data-sbnayy?file=app%2Fapp.component.html
enter image description here

最佳答案

全部 structural directives那样做是因为它们是基于 <ng-template>
这:

<hello name="1" *ngIf="true"></hello>
只是简化的语法
<ng-template [ngIf]="true">
<hello name="1"></hello>
</ng-template>
<ng-template>在没有被指示这样做的情况下不会被渲染。
你的情况到底发生了什么:
  • app.component 已经创建并通过 OnInit => DoCheck => AfterContentInit => AfterContentChecked 生命周期 Hook 。
  • hello.components 是 app.component 的内容(子项),它们应该被初始化,但在底层 *ngIf 将 "hello1"和 "hello2"包装到 <ng-template> .记住这一点。
  • 现在 app.component 的子组件通过相同的生命周期 Hook (OnInit 到 AfterContentChecked)。 Angular 不插入 <ng-template> 's 进入 DOM 但占位符(您可以在文档树中看到它作为注释):

  • 然后初始化“hello3”、“hello4”和“hello5”,插入DOM并执行console.log(this.name)
  • ngIf 指令和 hello.components(3 到 5)的时间初始化它们自己的内容。此时 hello.components (1 和 2) 在各自的 ngIf 指令中被初始化,在它们的占位符之后插入 DOM 并执行 console.log(this.name)
  • 然后 AfterViewInit => AfterViewChecked 钩子(Hook)从树中非常深的子节点冒出,您会看到渲染页面
  • 关于javascript - 为什么 Angular 组件的实例化顺序与 if 条件不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68495520/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com