Creating Custom Data Directives
Step 1: Build an Attribute Directive
Example: Auto-Format Text on Input
- Create the directive:
ng generate directive autoFormat
- Define its behavior:
// auto-format.directive.ts
@Directive({
selector: '[appAutoFormat]'
})
export class AutoFormatDirective {
@HostListener('input', ['$event']) onInput(event: Event) {
const input = event.target as HTMLInputElement;
input.value = input.value.toUpperCase();
}
}
- Use it in a template:
<input appAutoFormat placeholder="Type in uppercase">
Step 2: Build a Structural Directive
Example: Delay Element Rendering
- Create the directive:
ng generate directive delayRender
2.define logic:
// delay-render.directive.ts
@Directive({
selector: '[appDelayRender]'
})
export class DelayRenderDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input() set appDelayRender(delay: number) {
setTimeout(() => {
this.viewContainer.createEmbeddedView(this.templateRef);
}, delay);
}
}
3.use it in template:
<div *appDelayRender="2000">This content renders after 2 seconds.</div>
No comments