【问题标题】:How to make autofocus by angular 7 on click a button如何在单击按钮时通过角度 7 进行自动对焦
【发布时间】:2020-01-04 11:02:51
【问题描述】:

我的表格中有一些文本框来自循环。最初这些文本框被禁用,单击编辑按钮后它将被启用。直到现在工作正常。但我想在第一行的第一个文本框中自动对焦我点击编辑按钮。我尝试使用自动对焦属性,但它不起作用。任何人都可以帮助我。这是下面的代码

app.component.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);
}

【问题讨论】:

    标签: html angular


    【解决方案1】:

    你应该 @ViewChild 装饰器选择第一个文本框,然后使用 NativeElement 的焦点方法来聚焦。 请注意,setTimeout 用于给出布尔值的执行时间。

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

    【讨论】:

    • 感谢您的回答,我们可以在文本框聚焦的整行中放置蓝色边框吗?假设第一行的文本框被聚焦,所以当我们关注任何文本时,表格的整个第一行都会是蓝色的第二行的框整个表格的第二行应该有边框..等等
    • 我收到此错误---- src/app/app.component.ts(10,23) 中的错误:错误 TS2345:类型参数 '{ stat ic: boolean; }' 不能分配给 '{ read?: any; 类型的参数。 }'。对象字面量只能指定已知属性,而 '{ read?: any; 类型中不存在 'static' }'。
    • 从@ViewChild() 中删除静态:false 或升级到 angular 8
    • 我认为您应该在此答案中包含代码的“核心”(以及指向 stackblitz 的链接),以防该链接将来可能无法正常工作。 Anw,它就像一个魅力,谢谢。
    • @Anh-ThiDINH 感谢您的建议。下次我会考虑的。
    猜你喜欢
    • 1970-01-01
    • 2014-07-18
    • 2021-07-02
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多