簡體   English   中英

angular2 - 如何 DOM select 動態創建元素並聚焦它?

[英]angular2 - How to DOM select a dynamically created element and focus it?

我有一個動態的 HTML 元素列表,它們都有一個特定的屬性(例如'role=option')。

我想 select 第一個元素並給它焦點 在 angular 1 中,可以通過:

angular.element(document.querySelector('[role="option"]')).focus()

在 angular2 中,我找不到等效的方法。 所有答案似乎都涉及 viewChild 並為元素提供特定的#ref ,但 HTML 是通過*ngFor動態創建的,因此每個元素最終都會在循環中使用相同的#ref

這個怎么做?

您仍然可以使用模板引用變量並使用ViewChildrenfirst屬性來關注QueryList中的第一個元素。 嘗試以下

模板

<ng-container *ngFor="let item of items; let i=index">
  <input #input (change)="templateRefVariable(input.value)"/>
  <br />
</ng-container>

Controller

import { Component, TemplateRef, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  items = ['item1', 'item2', 'item3', 'item4'];
  @ViewChildren('input') inputElems: QueryList<ElementRef>;

  templateRefVariable(value) {
    console.log(value);
  }

  ngAfterViewInit() {
    this.inputElems.first.nativeElement.focus();
  }
}

工作示例: Stackblitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM