I'm using Angular v8 and Angular Materials. In particular mat-tab-group and mat-tab. I want to have something like the below. I want to be able to click on the "+" (which looks like a tab) and the result would be that it would create a new tab
After clicking on the "+" we'd see as below (focus is on the new tab we just added)
If I have a button above the mat-tab-group (which adds a new tab) all works fine but we want the "+" to be at the end of the tab list (as shown above). I can get the tab to create but focus doesn't got to it.
My code looks like. In the setSelectedIndex method call I add a new customer object and then set the selectedIndex to it. But no joy. Code sample below. Can try add as a plunkr if needs be
<mat-tab-group
class="no-vertical-scroll"
[disableRipple]="true"
animationDuration="0ms"
(selectedTabChange)="setSelectedIndex($event)"
(focusChange)="onFocusChange($event)"
[selectedIndex]="selectedTabIndex"
style="margin-top: 10px;">
<mat-tab *ngFor="let customer of customers; let index = index"
class="fullHeight no-vertical-scroll no-horizontal-scroll">
<div>
content for each tab
</div>
</mat-tab>
<mat-tab tooltip="New Tab" class="fullHeight no-vertical-scroll" label="New Tab">
<ng-template mat-tab-label class="fullWidth">
<span><mat-icon>add</mat-icon></span>
</ng-template>
</mat-tab>
</mat-tab-group>
Thanks Ro
You can try creating tabs using an array and bind it using ngFor, Then you can alter the array which will reflect changes into your tabs such as adding and removing.
Check the following example:
<div>
<button mat-raised-button
class="example-add-tab-button"
(click)="addTab(selectAfterAdding.checked)">
Add new tab
</button>
<mat-checkbox #selectAfterAdding> Select tab after adding </mat-checkbox>
</div>
<mat-tab-group [selectedIndex]="selected.value"
(selectedIndexChange)="selected.setValue($event)">
<mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab">
Contents for {{tab}} tab
</mat-tab>
<mat-tab disabled>
<ng-template mat-tab-label>
<button mat-icon-button (click)="addTab(selectAfterAdding.checked)">
<mat-icon>add_circle</mat-icon>
</button>
</ng-template>
</mat-tab>
</mat-tab-group>
Ts file
tabs = ['First', 'Second', 'Third'];
selected = new FormControl(0);
addTab(selectAfterAdding: boolean) {
this.tabs.push('New');
if (selectAfterAdding) {
this.selected.setValue(this.tabs.length - 1);
}
}
removeTab(index: number) {
this.tabs.splice(index, 1);
}
stackblitz Example
Updated
you can add a + button located last in the tabs by adding a tab after the array containing the actual tabs as follows:
<mat-tab disabled>
<ng-template mat-tab-label>
<button mat-icon-button (click)="addTab(selectAfterAdding.checked)">
<mat-icon>add_circle</mat-icon>
</button>
</ng-template>
</mat-tab>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With