0

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.

Justin
  • 1,050
  • 11
  • 26
  • So you want to differentiate if the `switchMode` method was triggered from `ngOnInit` or due to user action? – Aqeel Ashiq Aug 26 '22 at 14:35
  • If you change it programmatically only once and your loading is true, it should work. Place this.loading = false after if(conditionA){} When switchMode activates but loading is true - programatically changed tab, when false - user manually changed tab. – Taras Aug 26 '22 at 14:45
  • @Taras I just tried, didn't work, because the switchMode is trigged by async Angular event, loading is always false in switchMode method – Justin Aug 26 '22 at 18:24

1 Answers1

0

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
    }
  }
Justin
  • 1,050
  • 11
  • 26