简体   繁体   English

无法从父组件获取子元素

[英]Can't get child element from parent component

Im trying to get a child element from parent component with @ViewChild , but I got a problem, because my child component must be launched from parent function. 我试图使用@ViewChild从父组件中获取子元素,但是遇到了一个问题,因为我的子组件必须从父函数中启动。 And after such thing I cant get a child. 发生这样的事情之后,我无法生孩子。 It works fine, when child component starts with ngOnInit or whatever, but doesn't work with my function... What am I doing wrong and how to get it work? 当子组件以ngOnInit或其他任何形式但不能与我的函数一起使用时,它工作正常……我在做什么错以及如何使它工作?

My parent comp: 我的父母补偿:

export class MainScreenComponent {

    @ViewChild('myChild') child;
    showMyChild = false;

    getMyChild() {
        this.showMyChild = true;
        console.log(this.child.mytest); //undefined
    }

}

My parent temp: 我父母的临时工:

<button (click)="getMyChild()">Start My Child Comp</button>
<hr>
<div *ngIf="showMyChild==true">
    <div my-child #myChild></div>
</div>

My child comp: 我的孩子

@Component({
    selector: '[my-child]'
})

export class StdOrderComponent {
    mytest = 'This goes to parent';
}

Your varibale to child component is not initialized because <div my-child #myChild></div> is not in the DOM when showMyChild = false . 您的子级组件未初始化,因为<div my-child #myChild></div>showMyChild = falseshowMyChild = false DOM中。

I know 2 solutions: 我知道2个解决方案:

  1. Use [hidden] instead of *ngIf , so element is always there, but hidden 使用[hidden]而不是*ngIf ,因此element始终存在,但隐藏
<div [hidden]="showMyChild">
    <div my-child #myChild></div>
</div>
  1. Handle AfterView https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview (I could be wrong about exact life-cycle hook) in order to catch the moment when child component is added to the DOM. 处理AfterView https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview (确切的生命周期挂钩我可能错了),以赶上添加子组件的时刻到DOM。

PS You don't need to compare a boolean variable with true : PS您不需要将boolean变量与true进行比较:

*ngIf="showMyChild==true" is the same as *ngIf="showMyChild" *ngIf="showMyChild==true"与* ngIf =“ showMyChild”

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

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