简体   繁体   中英

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. 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?

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 .

I know 2 solutions:

  1. Use [hidden] instead of *ngIf , so element is always there, but hidden
<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.

PS You don't need to compare a boolean variable with true :

*ngIf="showMyChild==true" is the same as *ngIf="showMyChild"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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