Angular material mat-tab-group is changing active tab on textarea blur but not firing selectedIndexChange?

Viewed 1267

Given the following on the component:

formValues = ['aaa', 'bbb', 'ccc'];
log = (value) => console.log(value);

and this HTML:

<mat-tab-group (selectedIndexChange)="log($event)">
        <mat-tab *ngFor="let formVal of formValues; let indexOuter = index;"
                 label="Button {{indexOuter + 1}}">
            <textarea matInput
                      [value]="formVal"
                      (change)="formValues[indexOuter] = $event.target.value">
            </textarea>
        </mat-tab>
    </mat-tab-group>

When adding text to the first tab's text area and then changing the tab for the first time the text area text does not change and does not call the log function. Upon farther investigation when changing text in the first tab's text area and simply clicking anywhere outside of the text area but not clicking a tab header, the tab changes to tab 2 but again log does not run.

Since selectedIndexChange is clearly not running the index does not update and this appears to be the cause of my bug.

Any idea would be appreciated

EDIT: it looks like its because the data backing the mat-tab output via ngFor is getting edited by the textarea change and this seems like a bad idea, although I dont know why it causes such an issue.

1 Answers

This is happening because you are mutating the array which *ngForis iterating.

You need to change your array of string to an array of objects and change a property of each object, because in this case, the array element does not change, what changes is a property and it does not affect the *ngFor behavious.

Here is a live example: https://stackblitz.com/edit/angular-qhhcpi?file=app%2Ftab-group-basic-example.ts

Related