我有一个自定义指令,用于评估用户访问组件的权限,比如说
ngIfPerm
。
set ngIfPerm(val) {
// set val
if (/*true condition*/) {
this.viewContainer.createEmbbededView(this.templateRef)
} else {
this.viewContainer.clear()
}
}
此指令被放置在一些在表格行上重复的按钮中,以决定是否应呈现和显示该按钮。例如,如果用户具有
EDIT
权限,则此按钮会出现在表格的每一行上:
<button *ngIfPerm="EDIT" (click)="edit(rowData)>Edit</button>
问题是,Angular 重新渲染了这个按钮,而不是在表格的第二行重用它。如果按钮放置在多个位置,这会导致应用程序的性能急剧下降。
我的问题是,是否有一种机制可以帮助在第一次成功渲染后缓存此按钮并在再次调用时重用它? (就像缓存的模板)
我读过有关
templateCache
的内容,但它是针对 AngularJS 的,我正在将 Angular9 与 TypeScript 结合使用。
提前致谢。
这应该会提高应用程序的性能,因为 Angular 将不再需要在表格的每一行上重新渲染按钮。
import { TemplateCacheService } from '@angular/compiler';
@Directive({
selector: '[ngIfPerm]',
})
export class NgIfPermDirective {
constructor(private templateCacheService: TemplateCacheService) {}
set ngIfPerm(val) {
// set val
if (/*true condition*/) {
const cachedTemplate = await this.templateCacheService.cacheTemplate(this.templateRef.elementRef);
this.viewContainer.createEmbeddedView(cachedTemplate);
} else {
this.viewContainer.clear();
}
}
}