The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this:

Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define

[selectedIndex]="condition"
on the steppers, but I thought it should work differently. Any help would be appreciated.

<div *ngIf="!isSmallScreen; then horizontalStepper else verticalStepper"></div>

verticalStepper:

<ng-template #verticalStepper>
 <mat-vertical-stepper [linear]="isLinear"
                    style="z-index: 1; display: inline;"
                    class="container-fluid width-limit">
      <mat-step [completed]="condition1"></matstep>
      <mat-step [completed]="condition2"></matstep>
 </mat-vertical-stepper>
</ng-template>

horizontalStepper:

<ng-template #horizontallStepper>
 <mat-horizontal-stepper [linear]="isLinear"
                     style="z-index: 1; display: inline;"
                     class="container-fluid width-limit">
       <mat-step [completed]="condition1"></matstep>
       <mat-step [completed]="condition2"></matstep>
 </mat-vertical-stepper>
</ng-template>

This is the parent function responsible for handling the Selected Index:

ngAfterViewInit() {
  if (!conition1) {
    this.move(0);
  } else if (condition1) {
    this.move(1);
  } else if (condition2) {
    this.move(2);
  } 
}

This function is supposed to set the index but doesn't seem to be working:

move(index: number) {
  if (this.isSmallScreen) {
    this.verticalStepper.selectedIndex = index;
  } else {
    this.horizontalStepper.selectedIndex = index;
  }
}

As for the variable 'smallscreen':

@HostListener('window:resize', ['$event'])
  onResize(event) {
    if (event.target.innerWidth >= 600) {
      this.isSmallScreen = false;
    } else {
      this.isSmallScreen = true;
    }
  }

These are my ViewChildren:

export class GuidedSearchComponent implements OnInit, AfterViewInit {

  @ViewChild('verticalStepper') verticalStepper: MatStepper;
  @ViewChild('horizontalStepper') horizontalStepper: MatStepper;

Answer №1

I managed to solve the problem. Why don't you give it a shot?


<mat-vertical-stepper [linear]="true" #stepper [disableRipple]="true">
  <ng-container
    *ngFor="let partnerList of flowTemplates$ | async;let index = index;let last = last;"
  >
    <ng-container *ngIf="last;else others">
      <mat-step
        #step
        [editable]="false"
        [color]="(status === 4 || status === 5)?'accent':'primary'"
        [state]="(status === 4 || status === 5) ? 'fail' : 'number'"
      >
        <ng-template matStepLabel>
          <label>
            {{ status === 4 || status === 5 ? 'refused' : status === 3 ?
            'passed' : partnerList.name}}
          </label>
          <div>{{ partnerList?.date }}</div>
        </ng-template>
      </mat-step>
    </ng-container>
    <ng-template #others>
      <mat-step
        #step
        [color]="(status === 4 || status === 5)?'accent':'primary'"
        [editable]="false"
        [completed]="index<=nextIndex"
        [state]="'number'"
      >
        <ng-template matStepLabel>
          {{index}} {{currentIndex}} {{nextIndex}}
          <label>
            {{ last ? status === 4 || status === 5 ? 'refused' : status === 3 ?
            'passed' : partnerList.name : partnerList.name}}
          </label>
          <div>{{ partnerList?.date }}</div>
        </ng-template>
      </mat-step>
    </ng-template>
  </ng-container>
  <ng-container *ngIf="status===3">
    <ng-template matStepperIcon="number">
      <mat-icon role="img" class="mat-icon mat-icon-no-color" aria-hidden="true"
        >done</mat-icon
      >
    </ng-template>
  </ng-container>
</mat-vertical-stepper>

  @ViewChildren(MatStep) step?: QueryList<MatStep>;
  @ViewChild('stepper') stepper: MatHorizontalStepper;
  status = 3;

  flowTemplates$: Observable<Temp[]> = of(MOCKS).pipe(
    debounceTime(1000),
    tap((res) => {
      setTimeout(() => {
        const index = 4;
        const steps = this.step!.toArray();

        for (let i = 0; i < index - 1; i++) {
          steps[i].completed = true;
          this.stepper?.next();
        }
      }, 100);
    })
  );

Check out the result on this StackBlitz link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for integrating Material-Ui Autocomplete with Formik's Field component to create Multi-Select check boxes

Trying to integrate Formik's Field component with Material-Ui Autocomplete for multiple values that include checkboxes has been challenging. Whenever a value is selected from the dropdown list, the popup closes and needs to be reopened for the next se ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

Issue with Ng test: The type definition file for '@angular/localize' cannot be located

When upgrading from Angular 14 to 17, I ran into an issue with the ng test command. It seems to be malfunctioning now. Error: PS C:\ForAngular17\src\ng\cat-ng> ng test One or more browsers configured in the project's Browsersli ...

Is it possible to save or write a text file in the VueJs renderer process without the need to open the dialog box?

Currently, I am working on a project using VueJs + electron, where I need to save a text file to the user's PC without any prompt or dialog box popping up. I am aware of how to do this using require('fs'), but unfortunately fs does not work ...

Restricting a generic parameter to a combination type in Typescript

Is there a method in Typescript to restrict a generic parameter to only accept a union type? To clarify my question, I wish that T extends UnionType would serve this purpose: function doSomethingWithUnion<T extends UnionType>(val: T) {} doSomethingW ...

Error: The class you are attempting to access is

Currently, I am utilizing Vite.js along with TypeScript. My TypeScript file is located in 'src/vmodel/VGraph'. Within the index.html file, I import the aforementioned file as follows: <script type="module" src="/src/vmodel/VGrap ...

Is it possible to insert an image directly into the <img> tag without having to first send it to the server?

I've created an upload form that allows users to submit images: <form> <input accept="image/jpeg, image/gif, image/png" type="file" name="image" id="image" class="UploadInput" onchange="submitImageUploaderForm()"/> </form> Once t ...

Displaying queries using ajax in Rails

Can someone assist me in dealing with a particular issue? I am using ajax to refresh queries from the database dynamically each time there is a change in a search form. The main objective is to load N number of records based on the parameters selected in ...

retrieving form data from a submit button using objects in PHP

I am using objects to fetch a form (including a submit button) from another page. However, I am struggling to extract the POSTED information from that submit button and believe that AJAX might be necessary. Here is an example: Page 1 initiates a call to ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

I make a commitment to continue working until the issue is resolved and the page is successfully changed in the Protractor

I have a table with rows and I need to click on the edit button in a row that has a specific label (test server label). This is my function: public selectOnRow( textSelector:string , clickableSelector : string , value:string) { let promise = new Prom ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Activate the reactive forms when the checkbox is selected

Can you help me with enabling rows only when the checkbox is checked? I want the default rows to be disabled, but when the checkbox is checked, that specific row should become enabled. Here's the link to my code: CHECK OUT THE CODE HERE updateValu ...

How come pagination links in Vue.js 2 return JSON when clicked?

My question relates to having 2 specific components: Firstly, there is a component called SearchResultVue.vue. The structure of this component is as follows : <template> ... <span class="pull-right" v-show="totalall>8"> ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

Scanning barcodes with Angular using a gadget

Currently in the process of integrating barcode scanning into my Angular project. I have already installed @zxing/ngx-scanner, however, I have noticed that the performance is not up to par and it doesn't seem to work with an external scanner device - ...

Troubleshooting Electron Angular Application Connectivity Issues with API

While developing my ionic/angular app as an electron app, I encountered a problem when running it. After loading, I received the error message shown below: Refused to connect to 'https://xxxxxxxxxx.com/whpacking/v1/getlocations' because it violat ...