Created
June 9, 2020 14:31
-
-
Save armanozak/0d69a8fa5c1f4193ae399b28d20c9b2b to your computer and use it in GitHub Desktop.
[Attribute Directives to Avoid Repetition in Angular] The Adapter Directive #blog #angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Directive({ | |
// tslint:disable-next-line | |
selector: 'ngx-datatable[list]', | |
exportAs: 'ngxDatatableList', | |
}) | |
export class NgxDatatableListDirective implements OnChanges, OnDestroy, OnInit { | |
private subscription = new Subscription(); | |
@Input() list: ListService; | |
constructor(private table: DatatableComponent, private cdRef: ChangeDetectorRef) { | |
this.table.externalPaging = true; | |
this.table.externalSorting = true; | |
} | |
private subscribeToPage() { | |
const sub = this.table.page.subscribe(({ offset }) => { | |
this.list.page = offset; | |
this.table.offset = offset; | |
}); | |
this.subscription.add(sub); | |
} | |
private subscribeToSort() { | |
const sub = this.table.sort.subscribe(({ sorts: [{ prop, dir }] }) => { | |
this.list.sortKey = prop; | |
this.list.sortOrder = dir; | |
}); | |
this.subscription.add(sub); | |
} | |
private subscribeToIsLoading() { | |
const sub = this.list.isLoading$.subscribe(loading => { | |
this.table.loadingIndicator = loading; | |
this.cdRef.markForCheck(); | |
}); | |
this.subscription.add(sub); | |
} | |
ngOnChanges({ list }: SimpleChanges) { | |
if (!list.firstChange) return; | |
const { maxResultCount, page } = list.currentValue; | |
this.table.limit = maxResultCount; | |
this.table.offset = page; | |
} | |
ngOnDestroy() { | |
this.subscription.unsubscribe(); | |
} | |
ngOnInit() { | |
this.subscribeToPage(); | |
this.subscribeToSort(); | |
this.subscribeToIsLoading(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment