I know providing a ng-template for nzShowTotal is easy, but we have more than 80 nz-tables. Most of them needs pagination and requires nzShowTotal, which result in duplicated nz-template.
我们的项目里面有 80 多个 nz-table,几乎每个 table 都涉及分页,需要显示总条数。给 nzShowTotal 写一个 ng-template 很简单,但是写 80 遍就不是一个简单的事情,大量重复代码,而且很难要求所有人都统一风格。
<nz-table [nzShowTotal]="true"></nz-table>
can be translated into
<nz-table [nzShowTotal]="totalTemplate"></nz-table>
<ng-template #totalTemplate let-total>
共 {{total}} 条 <!-- should be translated -->
</ng-template>
Found a solution.
@Directive({
selector: '[showTotal]',
})
export class ShowTotalDirective implements OnInit {
templates: GlobalTemplatesComponent;
@Input() showTotal: string;
constructor(
@Optional() private pagination: NzPaginationComponent,
@Optional() private table: NzTableComponent,
componentFactoryResolver: ComponentFactoryResolver,
viewContainerRef: ViewContainerRef,
) {
const componentFactory = componentFactoryResolver.resolveComponentFactory(GlobalTemplatesComponent);
const componentRef = viewContainerRef.createComponent(componentFactory);
this.templates = componentRef.instance;
}
ngOnInit(): void {
const { totalTemplate, rangeTemplate } = this.templates;
switch (this.showTotal) {
case 'rangeTemplate':
this.setTemplate(rangeTemplate);
break;
case 'totalTemplate':
default:
this.setTemplate(totalTemplate);
break;
}
}
setTemplate(template) {
if (this.pagination) {
this.pagination.nzShowTotal = template;
} else if (this.table) {
this.table.nzShowTotal = template;
}
}
}
@EntryComponent()
@Component({
template: `
<ng-template #totalTemplate let-total>共 {{total}} 条</ng-template>
<ng-template #rangeTemplate let-range="range" let-total>显示第 {{range[0]}}-{{range[1]}} 条,共 {{total}} 条</ng-template>
`,
})
export class GlobalTemplatesComponent {
@ViewChild('totalTemplate') public totalTemplate: TemplateRef<{ $implicit: number, range: [ number, number ] }>;
@ViewChild('rangeTemplate') public rangeTemplate: TemplateRef<{ $implicit: number, range: [ number, number ] }>;
}
Usage
<nz-table [showTotal]></nz-table>
But it's like a dirty hack. I'm keeping this issue open for official support
duplicated
plz track #2200
Most helpful comment
Found a solution.
Usage
But it's like a dirty hack. I'm keeping this issue open for official support