coreui-angular-ex
Version:
CoreUI Components Library for Angular
140 lines (118 loc) • 3.2 kB
text/typescript
import {
ChangeDetectorRef,
Directive,
HostBinding,
HostListener,
Input,
OnChanges,
OnDestroy,
SimpleChanges
} from '@angular/core';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { Subscription } from 'rxjs';
import { TabService } from './tab.service';
export class TabContentRefDirective implements OnChanges, OnDestroy {
constructor(
private changeDetectorRef: ChangeDetectorRef,
private tabService: TabService
) {
this.subscribeTabService();
}
static ngAcceptInputType_disabled: BooleanInput;
private tabServiceSubscription!: Subscription;
/**
* Template Ref
* @type TemplateRef
*/
tabContentRef!: any;
/**
* Set active state of tab content
* @type boolean
*/
set active(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (this._active !== newValue) {
this._active = newValue;
this.changeDetectorRef.detectChanges();
}
}
get active() {
return this._active;
}
private _active = false;
/**
* Set disabled state of tab content
* @type boolean
*/
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
}
get disabled(): boolean {
return this._disabled || this.tabPaneIdx >= this.tabContentRef?.panes?.length;
}
private _disabled = false;
/**
* c-tab-pane index respectively
* @type number
*/
tabPaneIdx = -1;
get hostClasses() {
return {
active: this.active,
disabled: this.disabled
};
}
get isDisabled(): boolean | null {
return this.disabled || null;
}
get attrDisabled() {
return this.disabled ? '' : null;
};
get getTabindex(): string | null {
return this.disabled ? '-1' : null;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['active']?.currentValue) {
this.setActiveTabPane();
}
}
toggleOpen($event: any): void {
$event.preventDefault();
this.setActiveTabPane();
}
setActiveTabPane() {
setTimeout(() => {
if (this.tabPaneIdx < this.tabContentRef.panes.length) {
this.active = true;
this.tabService.setActiveTabIdx({ tabContent: this.tabContentRef, activeIdx: this.tabPaneIdx });
} else {
this.active = false;
}
});
}
ngOnDestroy(): void {
this.subscribeTabService(false);
}
subscribeTabService(subscribe: boolean = true) {
if (subscribe) {
this.tabServiceSubscription = this.tabService.activeTabPaneIdx$.subscribe((tabContentState) => {
if (tabContentState.tabContent === this.tabContentRef) {
this.active = (tabContentState.activeIdx === this.tabPaneIdx);
}
});
} else {
this.tabServiceSubscription?.unsubscribe();
}
}
}