angularkendo-uikendo-tabstrip

How can I implement a close tab button in Kendo Tabstrip with Angular


I have a kendo-tabstrip and I need add the ability to close tabs. I created a directive myCloseTab and applied it to a button element inside the kendoTabTitle directive, and I am able to successfully listen for click events on that element. So far so good.

However, I do not see how to access the kendoTabStrip element so I can invoke kendoTabStrip.remove(i), where i is the index of the tab. I can reference this.elementRef from the click listener, but I don't think walking up the DOM tree is the ideal Angular approach.

Kendo TabStrip:

<kendo-tabstrip>
    <kendo-tabstrip-tab
        *ngFor="let tab of tabs"
        [selected]="tab.selected"
        [disabled]="tab.disabled">

        <ng-template kendoTabTitle >
            <span>{{ tab.title }}</span>
            <button myCloseTab></button>
        </ng-template>

        <ng-template kendoTabContent>
            <div>{{ tab.data }</div>
        </ng-template>

    </kendo-tabstrip-tab>
</kendo-tabstrip>

myCloseTab directive:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[myCloseTab]'
})
export class CloseTabDirective {

    @HostListener('click', ['$event']) onClick() {
        console.log(this.elementRef);
    }

    constructor(private renderer: Renderer2, private elementRef: ElementRef) {
        this.renderer.addClass(this.elementRef.nativeElement, 'closeIcon');
    }

}

Solution

  • You can make a reference in the element you want to access like this:

    <kendo-tabstrip #reference>
    <kendo-tabstrip-tab
        *ngFor="let tab of tabs"
        [selected]="tab.selected"
        [disabled]="tab.disabled">
    
        <ng-template kendoTabTitle >
            <span>{{ tab.title }}</span>
            <button myCloseTab></button>
        </ng-template>
    
        <ng-template kendoTabContent>
            <div>{{ tab.data }</div>
        </ng-template>
    
    </kendo-tabstrip-tab>
    

    and the you can access this in .ts file by doing this :

    @ViewChild('reference') tabStrip : KendoTabStripConstructor;
    

    then you'll be able to access the methods of the tabStrip Object including that remove method. Personally I never used Kendo but I already used this approach with one of the primeng components and it's working just fine. I just looked kendo up and I think it's the same principle as primeng so this should work for you.