itsource

Angular2 - 구성 요소 로드에 텍스트 상자 초점 맞추기

mycopycode 2023. 8. 20. 10:47
반응형

Angular2 - 구성 요소 로드에 텍스트 상자 초점 맞추기

Angular2(Beta 8)에서 부품을 개발하고 있습니다.구성 요소에는 텍스트 상자와 드롭다운이 있습니다.구성 요소가 로드되거나 드롭다운 변경 이벤트가 발생하는 즉시 텍스트 상자에 포커스를 설정하고 싶습니다.각도2에서 어떻게 이를 달성할 수 있을까요?다음은 구성요소에 대한 Html입니다.

<div>
    <form role="form" class="form-horizontal ">        
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>        
    </form>
</div>

단순 사용autofocusHTML5 속성은 'on load' 시나리오에서 작동합니다.

 <input autofocus placeholder="enter text" [(ngModel)]="test">

또는

<button autofocus (click)="submit()">Submit</button>

http://www.w3schools.com/TAgs/att_input_autofocus.asp

이 답변은 포스트 Angular 2에서 영감을 받았습니다: 새로 추가된 입력 요소에 초점을 맞춥니다.

Angular2에서 Html 요소에 포커스를 설정하는 단계

  1. 구성 요소에서 View 하위 항목 가져오기

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. 포커스를 설정할 html의 로컬 템플릿 변수 이름 선언

  3. ngingAfterViewInit() 또는 기타 적절한 수명 주기 후크 구현
  4. 다음은 포커스 설정에 사용한 코드입니다.

    ngAfterViewInit() {vc.first.nativeElement.focus()}
    
  5. 더하다#input액세스할 DOM 요소의 속성입니다.

///This is typescript
import {Component, Input, Output, AfterContentInit, ContentChild,
  AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';

export class AppComponent implements AfterViewInit,AfterViewChecked { 
   @ViewChildren('input') vc;
  
   ngAfterViewInit() {            
        this.vc.first.nativeElement.focus();
    }
  
 }
<div>
    <form role="form" class="form-horizontal ">        
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>        
    </form>
</div>

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

코드 "myInput.focus()"가 입력이 생성된 후 실행되기 때문에 이것이 가장 좋고 간단한 방법입니다.

경고: 이 솔루션은 양식에 단일 요소가 있는 경우에만 사용할 수 있습니다(사용자가 다른 요소를 선택할 수 없음).

원래 질문은 초기에 포커스를 설정하거나 나중에 이벤트에 대응하여 포커스를 설정하는 방법을 요청했습니다.이것에 접근하는 올바른 방법은 모든 입력 요소에 대해 설정할 수 있는 속성 지시문을 만든 다음 사용자 지정 이벤트를 사용하여 이 입력 요소에 포커스 메서드를 안전하게 트리거하는 것입니다.그러기 위해서는 먼저 지시문을 작성합니다.

import { Directive, Input, EventEmitter, ElementRef, Renderer, Inject } from '@angular/core';

@Directive({
    selector: '[focus]'
})
export class FocusDirective {
    @Input('focus') focusEvent: EventEmitter<boolean>;

    constructor(@Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
    }

    ngOnInit() {
        this.focusEvent.subscribe(event => {
            this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
        });
    }
}

nativeElement(웹 작업자 안전)에서 renderrer.invokeElementMethod를 사용합니다.또한 focusEvent가 입력으로 선언됩니다.

그런 다음 새 지침을 사용하여 입력 요소에 포커스를 설정할 템플릿이 있는 Angular 2 구성 요소에 다음 선언을 추가합니다.

public focusSettingEventEmitter = new EventEmitter<boolean>();

ngAfterViewInit() { // ngOnInit is NOT the right lifecycle event for this.
    this.focusSettingEventEmitter.emit(true);
}
setFocus(): void {
  this.focusSettingEventEmitter.emit(true);
}

다음과 같이 구성 요소 위에 이벤트 이미터를 가져오는 것을 잊지 마십시오.

import { Component, EventEmitter } from '@angular/core';

이 구성 요소의 템플릿에서 다음과 같이 새 [template] 특성을 설정합니다.

<input id="name" type="text" name="name" 
    [(ngModel)]="person.Name" class="form-control"
    [focus]="focusSettingEventEmitter">

마지막으로 모듈에서 다음과 같이 새 지침을 가져오고 선언합니다.

import { FocusDirective } from './focus.directive';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [AppComponent, AnotherComponent, FocusDirective ],
    bootstrap: [ AppComponent ]
})

요약: ngAfterViewInit 함수는 새 EventEmitter를 내보냅니다. 이 이미터를 템플릿의 입력 요소에 있는 [focus] 속성에 할당하고 이 EventEmitter를 새 디렉티브의 입력으로 선언하고 이 이벤트에 대한 구독으로 전달한 화살표 함수에서 포커스 메서드를 호출했으므로 입력 요소가 수신됩니다.구성 요소가 초기화된 후 setFocus가 호출될 때마다 vefocus를 선택합니다.

저는 제 앱에도 같은 필요성이 있었고, 이것은 광고대로 작동했습니다.http://blog.thecodecampus.de/angular-2-set-focus-element/ 에 감사드립니다.

초점을 설정하는 방법은 각도 2: 새로 추가된 입력 요소에 초점을 맞춥니다.

"load"의 경우 "on load"를 합니다.ngAfterViewInit()라이프사이클 콜백.

저는 약간 다른 문제가 있었습니다.저는 모달로 입력을 작업했고 그것은 저를 미치게 했습니다.어떤 제안된 해결책도 저에게 효과가 없었습니다.

이 문제를 찾을 때까지: https://github.com/valor-software/ngx-bootstrap/issues/1597

이 좋은 사람은 ngx-bootstrap modal에 포커스 구성이 있다는 힌트를 주었습니다.이 구성을 false로 설정하지 않으면 애니메이션 후 모달이 초점을 맞추고 다른 어떤 것에도 초점을 맞출 수 없습니다.

업데이트:

이 구성을 설정하려면 모달 div에 다음 특성을 추가합니다.

[config]="{focus: false}"

업데이트 2:

입력 필드에 포커스를 설정하기 위해 입력 필드에 ng-untouch가 있는 한 AfterView Checked 사이클마다 지침을 작성하고 포커스를 설정했습니다.

 ngAfterViewChecked() {
    // This dirty hack is needed to force focus on an input element of a modal.
    if (this.el.nativeElement.classList.contains('ng-untouched')) {
        this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }
}

또한, 이렇게 동적으로 수행할 수 있습니다.

<input [id]="input.id" [type]="input.type" [autofocus]="input.autofocus" />

입력 위치

const input = {
  id: "my-input",
  type: "text",
  autofocus: true
};

autoFocus 첫 번째 필드에 대한 지침

import {
  Directive,
  ElementRef,
  AfterViewInit
} from "@angular/core";

@Directive({
  selector: "[appFocusFirstEmptyInput]"
})
export class FocusFirstEmptyInputDirective implements AfterViewInit {
  constructor(private el: ElementRef) {}
  ngAfterViewInit(): void {
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");
    if (invalidControl) {
      invalidControl.focus();
    }
  }
}

저는 모든 브라우저에서 이러한 솔루션을 많이 사용하지 못했습니다.이것이 저에게 효과가 있었던 해결책입니다.

라우터 변경의 경우:

router.events.subscribe((val) => {
    setTimeout(() => {
        if (this.searchElement) {
            this.searchElement.nativeElement.focus();
        }
    }, 1);
})

그리고나서ngAfterViewInit()온로드 시나리오의 경우.

$(jquery)를 사용할 수 있습니다.

<div>
    <form role="form" class="form-horizontal ">        
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="txtname`enter code here`" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>        
    </form>
</div>

그러면 ints:

    declare var $: any;

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls: ['./my-comp.component.css']
    })
    export class MyComponent  {

    @ViewChild('loadedComponent', { read: ElementRef, static: true }) loadedComponent: ElementRef<HTMLElement>;

    setFocus() {
    const elem = this.loadedComponent.nativeElement.querySelector('#txtname');
          $(elem).focus();
    }
    }

언급URL : https://stackoverflow.com/questions/35790021/angular2-focusing-a-textbox-on-component-load

반응형