[FIXED] How to distinguish user event from code event in Angular MatTabChangeEvent

Issue

I have a page need to set target mat tab after API is called.

And I need to save tab selection when user change it.

But in the event handler, I have no way to distinguish user event from code event:

Template:

<mat-tab-group disabled [(selectedIndex)]="uiData.currentTab" (selectedTabChange)="switchMode($event)" >
   <mat-tab disabled label="Assignment"></mat-tab>
   <mat-tab disabled label="Allocation"></mat-tab>
</mat-tab-group>

TS code:


  ngOnInit(): void {
        this.service.getAllData(this.uiData).subscribe(v => {
            this.loading = false;
            if(conditionA){
                this.uiData.currentTab = 1; // will trigger switchMode() even mat tab is disabled
            }
       }, err => {
          this.loading = false;
          this.errorMsg = "failure: " + err;
    });
  }

  switchMode(event: MatTabChangeEvent): void {

    if(!this.loading){   // Async event, doesn't work, I have no way to distinguish user event from code event
      this.validHolder.markAsDirty();  // enable save button
    }else{
      console.log("don't mark dirty");
    }
    
    this.errorMsg= null;
  }

And I also found MatTabChangeEvent is not general JS event and doesn’t have isTrusted propertity

Am I also think to add MatTabGroup into myForm and let me use emitEvent, but I didn’t find a way to add it in.

Solution

Fixed by a special flag currentTabOnInit (it is not beautiful, but works) :

   ngOnInit(): void {
        this.service.getAllData(this.uiData).subscribe(v => {
            this.loading = false;
            if(conditionA){
                this.uiData.currentTab = 1; // will trigger switchMode() even mat tab is disabled
                this.currentTabOnInit= true;
            }
       }, err => {
          this.loading = false;
          this.errorMsg = "failure: " + err;
    });
  }

  switchMode(event: MatTabChangeEvent): void {

    if(this.currentTabOnInit){
      console.log("don't mark dirty");
      this.currentTabOnInit = false;
    }else{
      console.log("mark dirty");
      this.validHolder.markAsDirty();  // enable save button
    }
  }

Answered By – Justin

Answer Checked By – David Marino (FixeMe Volunteer)

Leave a Reply

Your email address will not be published.