새로 추가된 입력 요소에 초점을 맞춥니다.
나는 는 이 을 을 목록이 있는 새로운 Angular 2 앱을 .input 박스를 합니다. 사용자가 리턴키를 누르면 새 키를 추가합니다.input현재 편집 중인 상자의 바로 뒤에 있는 상자입니다.I(새는의에로새을면가다을새로2가다을ar새로r새m는ori을a,의d에y(n(면로)n,oyny input가까운 시일내에 상자.
어떻게 하면 그렇게 만들 수 있을까요?input새로 추가된 요소에 자동으로 포커스 변경을 적용합니까?
1 삭제 1:
또는, DOM을 생성하게 하는 모델 객체에 대한 참조를 얻을 수 있습니다.컴포넌트 코드에서 특정 모델 객체를 나타내는 DOM 요소를 검색할 수 있는 방법이 있습니까?
2 편집 2: 편집 2:
여기 이 일을 해낼 수 있는 제 암호가 있습니다. 2 :-)부 Angular 2게을하기에히를다이를다:) :-
app.WordComponent = ng.core
.Component({
selector: 'word-editor',
template:'<input type="text" [value]="word.word" (input)="word.update($event.target.value)" (keydown)="keydown($event)"/>',
styles:[
''
],
properties:[
'list:list',
'word:word'
]
})
.Class({
constructor:[
function() {
}
],
keydown:function(e) {
if(e.which == 13) {
var ul = e.target.parentNode.parentNode.parentNode;
var childCount = ul.childNodes.length;
this.list.addWord("").then(function(word) {
var interval = setInterval(function() {
if(childCount < ul.childNodes.length) {
ul.lastChild.querySelector('input').focus();
clearInterval(interval);
}
}, 1);
});
}
}
});
제가 그렇게 해도 된다면 @Sasxa 답변에 참여해서 당신이 찾는 것처럼 수정하겠습니다.
몇가지 변화
- 나는 a를 사용할 것입니다.
ngFor그래서 angular2는 새로운 입력을 직접 하는 대신에 추가합니다.주된 목적은 그것을 반복하기 위해 각2를 만드는 것입니다. ViewChild저는에요를 사용할 .ViewChildren속성이 있는 쿼리 목록을 반환합니다.이 속성은 관측 가능한 속성이며 요소가 변경된 후 반환됩니다.
가 에 해야 을 사용해야 합니다.queriese를 사용할 재산ViewChildren
요소
Component({
selector: 'cmp',
template : `
<div>
// We use a variable so we can query the items with it
<input #input (keydown)="add($event)" *ngFor="#input of inputs">
</div>
`,
queries : {
vc : new ng.core.ViewChildren('input')
}
})
마지막 요소에 집중합니다.
ngAfterViewInit: function() {
this.vc.changes.subscribe(elements => {
elements.last.nativeElement.focus();
});
}
은 ΔViewChildren Δ QueryList Δ Δ Δ Δ Δ Δ 등이 포함된 합니다.changes◦ 됩니다.변경될 때마다 구독하면 요소 목록이 반환됩니다.elements가 들어있습니다.last것들 에서) 이 경우 마지막 요소를할 때, 이우는막를른성는중들가 ()중들른( )를 사용합니다.nativeElement에 그리고 에서focus()
입력 요소 추가 순수한 편의를 위해 입력 배열은 다시 그리기 이상의 실질적인 목적이 없습니다.ngFor.
add: function(key) {
if(key.which == 13) {
// See plnkr for "this.inputs" usage
this.inputs.push(this.inputs.length+1);
}
}
우리는 배열에 더미 아이템을 밀어 다시 그립니다.
ES5 사용 예제: http://plnkr.co/edit/DvtkfiTjmACVhn5tHGex
ES6/TS 사용 예제: http://plnkr.co/edit/93TgbzfPCTxwvgQru2d0?p=preview
업데이트 29/03/2016
시간이 지나고, 상황이 명확해 졌으며, 배울 수 있는 최선의 방법이 항상 있습니다.몇 가지를 바꿔서 이 대답을 단순화했습니다.
- 사용하는 대신
@ViewChildren그리고 그것을 구독하는 것은 새로운 입력이 생성될 때마다 인스톨 될 지침을 만들었습니다. - 사용하고 있습니다.
Renderer웹 워커를 안전하게 만들 수 있습니다.원래 답변 액세스focus()직접적으로nativeElement그것은 낙담된 것입니다. - 이제 들어봅니다.
keydown.enter키 다운 이벤트가 간단해지므로 확인할 필요가 없습니다.which가치.
간단명료한.구성요소는 다음과 같습니다(아래 plnkrs에서 단순화, 전체 코드).
@Component({
template: `<input (keydown.enter)="add()" *ngFor="#input of inputs">`,
})
add() {
this.inputs.push(this.inputs.length+1);
}
그리고 지시는
@Directive({
selector : 'input'
})
class MyInput {
constructor(public renderer: Renderer, public elementRef: ElementRef) {}
ngOnInit() {
this.renderer.invokeElementMethod(
this.elementRef.nativeElement, 'focus', []);
}
}
보다시피 제가 전화하는 겁니다invokeElementMethod방아쇠를 당기다focus직접 접근하는 대신 요소에 접근할 수 있습니다.
이 버전은 원래 버전보다 훨씬 깨끗하고 안전합니다.
beta 12로 업데이트된 plnkrs
ES5 사용 예제: http://plnkr.co/edit/EpoJvff8KtwXRnXZJ4Rr
ES6/TS 사용 예제: http://plnkr.co/edit/em18uMUxD84Z3CK53RRe
2018년 업데이트
invokeElementMethod사용되지 않습니다.렌더러 대신 렌더러2를 사용합니다.
요소에 ID를 지정하면 selectRootElement:
this.renderer2.selectRootElement('#myInput').focus();
ViewChild를 보십시오. 여기 예가 있습니다.이것이 당신이 찾고 있는 것일 수도 있습니다.
import {Component, ViewChild} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<input #name>
</div>
`,
directives: []
})
export class App {
@ViewChild('name') vc: ElementRef;
ngAfterViewInit() {
this.vc.nativeElement.focus();
}
}
인라인 각도 코드를 사용하여 조건부 페인트 후 초점을 맞춥니다.
<span *ngIf="editId==item.id">
<input #taskEditText type="text" [(ngModel)]="editTask" (keydown.enter)="save()" (keydown.esc)="saveCancel()"/>
<button (click)="save()">Save</button>
<button (click)="saveCancel()">Cancel</button>
{{taskEditText.focus()}}
</span>
간단한 입력 텍스트 지시를 구현할 수 있으므로 새로운 입력이 생성될 때마다 자동으로 초점이 맞춰집니다.focus()를 method .ngAfterViewInit()뷰가 완전히 초기화된 후 컴포넌트 라이프사이클 후크.
@Directive({
selector: 'input[type=text]'
})
export class FocusInput implements AfterViewInit {
private firstTime: bool = true;
constructor(public elem: ElementRef) {
}
ngAfterViewInit() {
if (this.firstTime) {
this.elem.nativeElement.focus();
this.firstTime = false;
}
}
}
을 합니다.FocusInput구성 요소에 지시:
@Component({
selector: 'app',
directives: [FocusInput],
template: `<input type="text" (keyup.enter)="last ? addNewWord():0"
*ngFor="#word of words; #last = last" [value]="word.word"
#txt (input)="word.word = txt.value" />{{words |json}}`
})
export class AppComponent {
words: Word[] = [];
constructor() {
this.addNewWord();
}
addNewWord() {
this.words.push(new Word());
}
}
다음 사항에 유의합니다.
(keyup.enter)하는 데 됩니다. < > 키가 눌려질 때 < enter> 키가 눌릴 때 사용됩니다.ngFor각에력를서는데다한데fyes는각의 배열에서 각 단어에 대한 입력 요소를 하는 데 됩니다.wordslast이며, 때입니다.- 는 가 에 에 가
last ? addNewWord() : 0마지막 만 새 됩니다. 이렇게 하면 마지막 입력에서 <엔터> 키를 누를 때만 새 입력 필드가 추가됩니다.
동일한 주기로 여러 지시사항을 초기화할 때 초점을 맞출 요소의 우선순위를 정하려면 다음을 사용합니다.
지시:
@Directive({
selector: '[focusOnInit]'
})
export class FocusOnInitDirective implements OnInit, AfterViewInit {
@Input('focusOnInit') priority: number = 0;
static instances: FocusOnInitDirective[] = [];
constructor(public renderer: Renderer, public elementRef: ElementRef) {
}
ngOnInit(): void {
FocusOnInitDirective.instances.push(this)
}
ngAfterViewInit(): void {
setTimeout(() => {
FocusOnInitDirective.instances.splice(FocusOnInitDirective.instances.indexOf(this), 1);
});
if (FocusOnInitDirective.instances.every((i) => this.priority >= i.priority)) {
this.renderer.invokeElementMethod(
this.elementRef.nativeElement, 'focus', []);
}
}
}
용도:
<input type="text" focusOnInit="9">
https://plnkr.co/edit/T9VDPIWrVSZ6MpXCdlXF
언급URL : https://stackoverflow.com/questions/34522306/focus-on-newly-added-input-element
'programing' 카테고리의 다른 글
| 서피스 뷰와 뷰의 차이점은 무엇입니까? (0) | 2023.09.12 |
|---|---|
| php zip 내부의 파일에 대한 경로 없이 zip 생성 (0) | 2023.09.12 |
| MariaDB 쿼리 JSON 결과는 텍스트 열에서 \\"라는 큰따옴표를 벗어납니다. (0) | 2023.09.12 |
| int.TryParse합성당 (0) | 2023.09.12 |
| 리사이클러뷰를 사용하여 ListView를 대체해야 합니까? (0) | 2023.09.12 |