helloworld
helloworld

Reputation: 1042

ViewChild inside a dom if in Angular

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.

Upvotes: 3

Views: 223

Answers (1)

user4676340
user4676340

Reputation:

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.

Upvotes: 2

Related Questions