簡體   English   中英

單擊時將重點放在textarea angular 5上

[英]On click set focus on textarea angular 5

<div class="posts">    
   <div class="post">
      <div>post content</div>
    <a class="comment">Comment</a>

    <textarea [(ngModel)]= "model.text" class="comment-text" name="text"></textarea>
    </div>

    <div class="post">
       <div>post content</div>
    <a class="comment">Comment</a>

    <textarea [(ngModel)]= "model.text" class="comment-text" name="text"></textarea>
    </div>
</div>
...

我想將重點放在“ a”點擊上的textarea上。 誰能幫幫我嗎。 我正在使用角度5

在這里,您可以循環<div class="post">

<div class="posts">    
  <div class="post">
    <div>post content</div>
    // Pass index here, if you want to achieve dynamically
    <a class="comment" (click)="doSomething(0)">Comment</a>
    <textarea [(ngModel)]= "model.text" class="comment-text" #txtArea name="text"> 
    </textarea>
  </div>   
  <div class="post">
    <div>post content</div>
    <a class="comment" (click)="doSomething(1)">Comment</a>
    <textarea [(ngModel)]= "model.text" class="comment-text" #txtArea name="text"> 
    </textarea>
  </div>
</div>

現在在您的ts文件中添加以下導入,

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

像這樣使用ViewChildrenQueryList讀取元素,

@ViewChildren("txtArea") textAreas:QueryList<ElementRef>;

最后,您的doSomething事件處理程序是這樣的,

doSomething(index: number) {
  this.textAreas.find((item, idx) => {
    return idx === index;
  }).nativeElement.focus();
}

更新資料

上面的代碼將與一系列posts 因此,我們無需對ID進行硬編碼,例如#txtArea1,#txtArea2等。請在此處檢查DEMO_1

如果您像這樣重復<div class="post">

<div class="post" *ngFor="let post of posts; index as i">

您可以傳遞index (此處為i )以從QueryList獲取相應的TextArea引用,如下所示,

<a class="comment" (click)="textAreas.toArray()[i].nativeElement.focus()">Comment</a>

在此處檢查完整的代碼DEMO_2

您可以使用@ViewChild裝飾器。 文檔: https : //angular.io/api/core/ViewChild

您需要為輸入元素分配一個名稱,並關聯一個click事件。

<textarea #inputToFocus />
 <a (click)="focusInput()">Click</button>

在您的組件中,使用@ViewChild搜索元素,然后實現單擊處理程序以執行所需的操作。

export class App implements AfterViewInit {
  @ViewChild("inputToFocus") inputElement: ElementRef;

  focusInput() {
    this.inputElement.nativeElement.focus()
  }

注意: ngAfterViewInit事件觸發時, inputElement變量將首先可用。

由於問題已更新:要處理多個元素,您需要使用@ViewChildren文檔: https ://angular.io/api/core/ViewChildren

在上面給出的代碼示例中,我將冗余代碼放入其自己的組件中以封裝重復的功能。

如果使用模板變量,則可以直接從HTML文件中的標記設置焦點。 您可以在(click)方法中引用它。 這樣,無需通過代碼訪問DOM,它保留在HTML文件中,更易於調試:

的HTML

...
<textarea #textarea1 [(ngModel)]="text" class="comment-text" name="text"></textarea>
<button (click)="textarea1.focus()">SetFocus on the first textarea</button>
...
<textarea #textarea2 [(ngModel)]="text" class="comment-text" name="text"></textarea>
<button (click)="textarea2.focus()">SetFocus on the second textarea</button>
...

演示

暫無
暫無

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

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