Template controllers
Encapsulate templating logic in reusable controllers that coordinate rendering in Aurelia views.
Declaring a Template Controller
1. @templateController() decorator
@templateController() decoratorimport { bindable, ICustomAttributeController, IRenderLocation, ISyntheticView, IViewFactory, templateController } from '@aurelia/runtime-html';
import { resolve } from '@aurelia/kernel';
@templateController({
name: 'permission',
bindables: ['userRole', 'requiredRole'],
containerStrategy: 'reuse',
})
export class PermissionTemplateController {
public readonly $controller!: ICustomAttributeController<this>;
@bindable() public userRole = '';
@bindable() public requiredRole = '';
private readonly factory = resolve(IViewFactory);
private readonly location = resolve(IRenderLocation);
private view?: ISyntheticView;
public binding() {
this.view ??= this.factory.create().setLocation(this.location);
}
public bound() {
this.updateVisibility();
}
public userRoleChanged() {
this.updateVisibility();
}
public requiredRoleChanged() {
this.updateVisibility();
}
public detaching() {
this.view?.deactivate(this.view, this.$controller);
}
private updateVisibility() {
if (!this.view) {
return;
}
const canSee = this.userRole === this.requiredRole;
if (canSee && !this.view.isActive) {
void this.view.activate(this.view, this.$controller, this.$controller.scope);
} else if (!canSee && this.view.isActive) {
void this.view.deactivate(this.view, this.$controller);
}
}
}2. @customAttribute({ isTemplateController: true })
@customAttribute({ isTemplateController: true })3. Static $au definition / CustomAttribute.define
$au definition / CustomAttribute.defineManaging the Hosted View
Coordinating Multiple Template Controllers
Restrictions and Gotchas
Next Steps
Last updated
Was this helpful?