簡體   English   中英

如何在單擊按鈕時按角度 7 進行自動對焦

[英]How to make autofocus by angular 7 on click a button

我有一些來自循環的表中的文本框。最初這些文本框被禁用,單擊編輯按鈕后它將被啟用。直到現在工作正常。但是我想在單擊時在第一行的第一個文本框中自動對焦編輯按鈕。我嘗試使用自動對焦屬性,但它不起作用。任何人都可以幫助我。這是下面的代碼

應用程序組件.html

<div class="container">
    <h2>Basic Table</h2>
    <p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
    <div><button (click)="enable()">Edit</button> </div>
    <table class="table border">

        <tbody>
            <tr *ngFor="let row of groups;let i = index">
                <td> <input autofocus [disabled]='toggleButton' type="text" value="{{row.name}}"> </td>
                <td> <input [disabled]='toggleButton' type="text" value="{{row.items}}"> </td>
                <td> <button (click)="addRow(i)">Add</button></td>
            </tr>
        </tbody>
    </table>
</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    public toggleButton: boolean = true;
  ngOnInit() {

  }
  groups=[
     {
       "name": "pencils",
       "items": "red pencil"
     },
     {
       "name": "rubbers",
       "items": "big rubber"
     },
     {
       "name": "rubbers1",
       "items": "big rubber1"
     },
  ];
  addRow(index): void {
    var currentElement = this.groups[index];
    this.groups.splice(index, 0, currentElement);
 }
 enable(){
       this.toggleButton = false
    }
  //console.log(this.groups);
}

您應該 @ViewChild 裝飾器選擇第一個文本框,然后使用 NativeElement 的 focus 方法進行聚焦。 請注意, setTimeout 用於給出布爾值的執行時間。

工作示例https://stackblitz.com/edit/angular-table-focus

暫無
暫無

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

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