Angular ViewChild 未为子独立组件初始化

问题描述 投票:0回答:1

我有一个标记为独立的父组件。这会消耗另一个也是独立的子组件。父子都显示成功。

但是,即使在 AfterViewInit 上,ViewChild 变量也从未初始化。

仅在使用独立组件时才会出现此问题 - 请注意整个应用程序是独立的。 有人遇到过同样的问题并解决了吗

使用 Angular CLI 16.2.11

这是一些伪代码,我希望能够在子对象上调用 DoSomething 方法。


parent.html

<div>My main page</div>
<app-child></app-child>

child.html

<div>I am the child</div>


parent.ts

@Component({
  selector: 'parent',
  standalone: true,
  imports: [CommonModule, ChildComponent],
  templateUrl: './parent.html',
  styleUrls: ['./parent.scss']
})

export class parent  implements AfterViewInit {

@ViewChild(ChildComponent)
myChildComponent!: ChildComponent;

ngAfterViewInit(): void {

    // this is always undefined
  console.log(this.myChildComponent);
  
  this.myChildComponent.doSomething();
}


child.ts

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './child.html',
  styleUrls: ['./child.scss']
})

export class child  {

    public doSomething() : void{
    }
}
angular viewchild angular-standalone-components
1个回答
0
投票

似乎正在设置 ViewChild 引用,但在“真实”代码中的 AfterViewInit 之后,子级位于弹出窗口中,关闭时确实已分配值。

我猜管道还没有到达那里 - 在正在使用的代码中,最好将其描述为 main.ts 中的祖父母、父母、孩子。只是让确定绑定值的可用性变得更加困难。

© www.soinside.com 2019 - 2024. All rights reserved.