繁体   English   中英

ViewChild 在 angular 13 中未定义

[英]ViewChild is undefined in angular 13

我正在尝试从父组件调用子组件的视图子组件,并在控制台中获取 undefined 。

看到图像也看到相同的堆栈火焰

https://stackblitz.com/edit/angular-ivy-k4m2hp?file=src%2Fapp%2Fhello.component.ts

看到图像也看到相同的堆栈火焰

import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';

@Component({
  selector: 'hello',
  template: `<h1>this is Hello component {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  @Input() name: string;
@ViewChild('TestChildComponent') testChildComponent: TestChildComponent
  ngOnInit() {
    console.log('calling ngOninit in hello component');
    console.log('going to call test child instance this.TestChildComponent.ngOninit')
   console.log(this.testChildComponent);
  }
}

请帮助获取子组件

这个.testChildComponent

这样我就可以从父母那里打电话给孩子的 ngOnInit 。

this.testChildComponent.ngOnInit()

最早可以在ngAfterViewInit()循环中访问 ViewChild 元素 ref。

在此处输入图像描述

Angular 文档说我们应该在 ngAfterViewInit 中使用 ViewChild 注入的子组件。 但有时你甚至无法在 ngAfterViewInit 中获取它。 原因是 AfterViewInit 钩子运行时子组件尚未创建。 对于这种情况,您将不得不等待更多时间(使用setTimeout会起作用,但这是个坏主意)。 另一种选择是让孩子向父母发出一些东西,让它知道孩子已经被渲染,然后父母可以查询它。

但是你的情况是兄弟HelloComponent想要查询兄弟TestChildComponent它不能这样做。 TestChildComponent不在HelloComponent的 scope 中。 最简单的解决方案是从父AppComponent TestChildComponent

您还应该添加#TestChildComponent以访问 ref。

<app-test-child #TestChildComponent childname="{{ name }}"></app-test-child>

工作示例: https://stackblitz.com/edit/angular-ivy-j5ceat?file=src%2Fapp%2Fapp.component.html

如果你设置你的 viewChild { static: true } 你将能够在 ngOnInit 中访问它

但在您的示例中,问题是由于 testChildComponent 是 app.component 而不是 hello.component 的子项

<app-test-child childname="{{ name }}" #test></app-test-child>

应用程序组件.ts

import { Component, VERSION, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'this is from app compoenent';
  @ViewChild('test', { static: true }) testChildComponent: TestChildComponent;

  ngOnInit() {
    console.log('calling ngOninit in app component');
    console.log(this.testChildComponent);
  }
}

如果你想从 hello.component 访问 testChildComponent ,你必须将组件作为示例的输入发送给它

遵循访问 testChildComponent 的工作示例

https://stackblitz.com/edit/angular-ivy-tvwukg?file=src%2Fapp%2Fapp.component.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM