一旦 UI 在 Angular8 中完全渲染,如何进行一些操作

发布于 2025-01-10 02:27:18 字数 586 浏览 4 评论 0 原文

我只想在 UI 完全渲染后执行一些操作。

由于子组件来自库,因为未定义的

子组件来自库(来自另一个应用程序的组件作为依赖项添加)。所以我无法修改/增强子组件

my.html

<div>
  <h4>Parent</h4>
  <child-component  #childComponent></child-component>
</div>

my.component.ts

@ViewChild('childComponent', {read: ChildComponent, static: false}) private child: ChildComponent;

private myFunction(): void {
  console.log('child', this.child); // This prints undefined. 
  if(this.child) {
   // DO some operations
  }
}

I want to perform some operation only after UI completely rendered.

Since child component is coming as undefined

child-component is from library (component from another application added as dependency). So I can't modify/enhance child-component

my.html

<div>
  <h4>Parent</h4>
  <child-component  #childComponent></child-component>
</div>

my.component.ts

@ViewChild('childComponent', {read: ChildComponent, static: false}) private child: ChildComponent;

private myFunction(): void {
  console.log('child', this.child); // This prints undefined. 
  if(this.child) {
   // DO some operations
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果没结果 2025-01-17 02:27:18

你的代码已经足够好了,你只需要在子进程加载时触发 myFunction() 即可,这可以从 Angular 的 ngAfterViewInit 生命周期钩子中进行检查:

@ViewChild('childComponent', { static: false }) child: ChildComponent;
    
ngAfterViewInit() {
    this.myFunction();
}
    
myFunction(): void {
    console.log('child', this.child); // This prints undefined.
    if (this.child) {
        // DO some operations
    }
}

检查 https://stackblitz.com/edit/angular-parent-to-child-communication-avxqor 我已将 var 添加到子组件中,只是为了表明可以通过这种方式访问​​它,并添加了一个控制台。登录子进程的 OnInit 以显示子进程在父进程的 ngAfterViewInit 挂钩之前启动。

Your code is good enough, you just need to trigger myFunction() when the child is loaded, and that can be checked from Angular's ngAfterViewInit lifecycle hook:

@ViewChild('childComponent', { static: false }) child: ChildComponent;
    
ngAfterViewInit() {
    this.myFunction();
}
    
myFunction(): void {
    console.log('child', this.child); // This prints undefined.
    if (this.child) {
        // DO some operations
    }
}

Check https://stackblitz.com/edit/angular-parent-to-child-communication-avxqor I've added var into child component just to show that it's accessible this way, and added a console.log on child's OnInit to show that the child is initiated before parent's ngAfterViewInit hook.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文