s.spirit
s.spirit

Reputation: 343

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';
}

Upvotes: 0

Views: 291

Answers (1)

Andrei Zhytkevich
Andrei Zhytkevich

Reputation: 8099

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.

P.S. You don't need to compare a boolean variable with true:

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

Upvotes: 1

Related Questions