auto-focus.directive.ts
angular/comprehensive-demo/src/app/shared/directives/auto-focus.directive.ts
/**
* Auto Focus Directive
*
* This directive automatically focuses an element when it's rendered.
* Useful for:
* - Focusing input fields in forms
* - Focusing search boxes
* - Improving accessibility
*
* This demonstrates:
* - Element manipulation
* - Lifecycle hooks
* - Focus management
*/
import { Directive, ElementRef, Input, AfterViewInit, OnDestroy } from '@angular/core';
@Directive({
selector: '[appAutoFocus]',
standalone: true
})
export class AutoFocusDirective implements AfterViewInit, OnDestroy {
/**
* Input to control when to focus
* If true, element will be focused
*/
@Input() appAutoFocus: boolean = true;
/**
* Delay before focusing (in milliseconds)
* Useful for animations or when element is not immediately ready
*/
@Input() focusDelay: number = 0;
/**
* Timeout reference for cleanup
*/
private timeoutId: any;
/**
* Constructor
*/
constructor(private elementRef: ElementRef) {}
/**
* Lifecycle hook - called after view is initialized
*
* AfterViewInit is used instead of OnInit because we need
* the element to be in the DOM before we can focus it.
*/
ngAfterViewInit(): void {
if (this.appAutoFocus) {
// Use setTimeout to ensure element is fully rendered
this.timeoutId = setTimeout(() => {
const element = this.elementRef.nativeElement;
// Check if element is focusable
if (element && typeof element.focus === 'function') {
element.focus();
}
}, this.focusDelay);
}
}
/**
* Lifecycle hook - cleanup
*/
ngOnDestroy(): void {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
}
関連記事
server.js
server.js — javascript source code from the angular learning materials (angular/comprehensive-demo/server/server.js).
記事を読む →app.component.ts
app.component.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.component.ts).
記事を読む →app.config.ts
app.config.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.config.ts).
記事を読む →app.routes.ts
app.routes.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.routes.ts).
記事を読む →auth.guard.ts
auth.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/auth.guard.ts).
記事を読む →role.guard.ts
role.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/role.guard.ts).
記事を読む →