Home > Net >  Angular @ViewChild not getting mat-tab inner components
Angular @ViewChild not getting mat-tab inner components

Time:05-30

I have an Angular Material mat-tab-group, with 12 mat-tabs inside.

Inside each mat-tab, I have a particular component with an unique id. My component's tree looks like this:

<mat-tab-group>
    <mat-tab> <app-step-one #stepOne></app-step-one> </mat-tab>
    <mat-tab> <app-step-two #stepTwo></app-step-two> </mat-tab>
    <mat-tab> <app-step-three #stepThree></app-step-three> </mat-tab>
    ...
    <mat-tab> <app-step-twelve #stepTwelve></app-step-twelve> </mat-tab>
</mat-tab-group>

And, in my TS file, I'm referencing each app-step-* component with @ViewChild, and added all of them on an array, this way:

@ViewChild("stepOne") stepOne: StepOneComponent;
@ViewChild("stepTwo") stepTwo: StepTwoComponent;
@ViewChild("stepThree") stepThree: StepThreeComponent;
...
@ViewChild("stepTwelve") stepTwelve: StepTwelveComponent;

tabs[] = [
    this.stepOne,
    this.stepTwo,
    this.stepThree,
    ...
    this.stepTwelve
];

But, for some reason, the properties in my TS file are all undefined, and I can't use them to get my component's properties and methods, either inside and outside the array.

Can someone help me? I can't figure out why isn't working as expected.

CodePudding user response:

My problem was in Angular's life time. I've tried to populate the tabs array within the construct method. When I moved the population of tabs to ngAfterViewInit method, finally I reached the result I needed.

CodePudding user response:

You need to use ngAfterViewInit() Angular hook to get value from @ViewChild elements. See below ngAfterViewInit() { this.tab1 = this.stepOne; console.log('stepOne testConst = ', this.tab1.testConst); }. Here is a sample https://angular-ivy-7qz2xa.stackblitz.io

  • Related