3

I am trying to get a reference to an element which is inside dom-if using ViewChild. Actually I am using mat-stepper and want to navigate to 2nd step directly. Following is the snippets of my code;

.html

<mat-vertical-stepper #stepper *ngIf="showStepper"> 

component.ts

 @ViewChild('stepper') stepper: MatStepper; constructor() { } ngOnInit() { this.firstFormGroup = new FormGroup({ firstCtrl: new FormControl(null, [Validators.required]) }); this.secondFormGroup = new FormGroup({ secondCtrl: new FormControl(null, [Validators.required]) }); this.stepper.selectedIndex = 1; } 

I want to navigate to 2nd step(1st index) directly. For this I am using ViewChild, but since mat-stepper is inside a dom-if, this.stepper is coming out to be undefined. Here is the stackblitz link to my code:

Stackblitz link

Any help would be highly appreciated.

1 Answer 1

2

Use a Timeout to shift the execution, and use a condition to do it only if the stepper exists : stackblitz

setTimeout(() => this.stepper ? this.stepper.selectedIndex = 1 : null); 

Also, consider binding the click on your button to ngOnInit (although you should create a new function, that will be called by the button & ngOnInit). Also consider shifting that timeout into the subscribe.

If you don't display the data, there's no point in having it stored.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.