개발/front-end

angular 포커스 이동

희운1205 2023. 2. 13. 17:52
반응형

angular 포커스 이동 처리

 

import { Component, ViewChild, ElementRef, Directive, Renderer2 } from '@angular/core';

@Directive({
    selector: '[focus]'
})

export class FocusDirective  {
    constructor(public renderer: Renderer2) {
    }

    @HostListener('keyup.enter', ['$event'])
    public  onkeyenter(event: any): void {
        const selectEl = event.target;
        if (selectEl.getAttribute('next')) {
             const next = selectEl.getAttribute('next');
             const element = this.renderer.selectRootElement('#' + next);
             setTimeout(() => element.focus(), 0);
        }
    }
}

export class FormModel {
    public name!: string;
    public mobile!: any;
    public addr!: any;
}

@Component({
    selector: 'app-sample-form',
    template: `
     <div>
     <input type="text" id="name" #name name="name" [(ngModel)]="data.name"
     focus next="mobile" />
     <input type="text" id="mobile" name="mobile" [(ngModel)]="data.mobile"
     focus next="addr" />    
     <input type="text" id="addr" name="addr" [(ngModel)]="data.addr" />  
    `
    providers:  [ FocusDirective ]
})

public data: any;

@ViewChild('name') name!: ElementRef;
 
constructor() {
    this.data = new FormModel();    
}

public ngAfterViewInit(): void {
       if (this.name) {
           this.name.nativeElement.focus();
       }
}
반응형