Angular2-구성 요소로드시 텍스트 상자 집중 <div class=”col-md-7 col-sm-7″>

Angular2 (Beta 8)에서 구성 요소를 개발 중입니다. 구성 요소에는 텍스트 상자와 드롭 다운이 있습니다. 구성 요소가로드되거나 드롭 다운의 변경 이벤트가 발생하자마자 텍스트 상자에 포커스를 설정하고 싶습니다. angular2에서 이것을 어떻게 얻을 수 있습니까? 다음은 구성 요소에 대한 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 속성을 사용하면 ‘로드시’시나리오에서 작동합니다.

 <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. 구성 요소에서 ViewChildren 가져 오기

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. 포커스를 설정하려는 html에 대한 로컬 템플릿 변수 이름을 선언합니다.

  3. ngAfterViewInit () 함수 또는 기타 적절한 라이프 사이클 후크 구현
  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에서 renderer.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);
}

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

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

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

<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를 방출하게하고,이 이미 터를 템플릿의 input 요소에있는 [focus] 속성에 할당했기 때문에이 EventEmitter를 새 지시문에 대한 입력으로 선언하고 포커스를 호출했습니다. 이 이벤트에 대한 구독에 전달한 화살표 함수의 메서드를 사용하면 구성 요소가 초기화 된 후 setFocus가 호출 될 때마다 입력 요소가 포커스를받습니다.

내 앱에서도 동일한 요구 사항이 있었으며 광고 된대로 작동했습니다. 다음에 대단히 감사합니다 : http://blog.thecodecampus.de/angular-2-set-focus-element/


답변

초점 을 설정하는 방법 은 Angular 2 : 새로 추가 된 입력 요소초점을 참조하십시오 .

“로드시”의 경우 ngAfterViewInit()수명주기 콜백을 사용합니다 .


답변

나는 약간 다른 문제가 있었다. 모달 에서 입력으로 작업했습니다. 했고 그것은 나를 미치게 만들었다. 제안 된 솔루션 중 어느 것도 저에게 효과가 없었습니다.

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

이 좋은 녀석은 ngx-bootstrap 모달 에 포커스 구성이 . 이 구성이 false로 설정되지 않은 경우 모달은 애니메이션 후에 초점이 맞춰지고 다른 것에 초점을 맞출 방법이 없습니다.

최신 정보:

이 구성을 설정하려면 모달 div에 다음 속성을 추가하십시오.

[config]="{focus: false}"

업데이트 2 :

입력 필드에 초점을 맞추기 위해 지시문을 작성하고 입력 필드에 ng-untouched 클래스가있는 한 모든 AfterViewChecked주기에서 초점을 설정했습니다.

 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
};