【问题标题】:*ngFor generated mat-button is focused on load*ngFor 生成的 mat-button 专注于加载
【发布时间】:2018-06-14 08:08:32
【问题描述】:

我正在使用 ngFor 生成一个按钮列表,当我加载网站时,第一个生成的按钮已经聚焦,直到我点击其他任何地方...

<div align="center" class="buttonDiv" *ngFor="let tamplates of caseService.availableTaskTemplates"> <button mat-button class="button" *ngIf="tamplates.contentType == 1" (click)="createTask(tamplates.taskType)"> {{ tamplates.headerText }} </button> </div>

这是一张图片: https://ibb.co/imG7sy

我可以做些什么来“取消焦点”按钮?

【问题讨论】:

    标签: html angular button focus


    【解决方案1】:

    您可以在 HTML 中使用 autofocus 属性。

    自动对焦:页面加载后聚焦在元素上

    将其添加到 HTML 中的虚拟元素中,以取消对元按钮的关注。

    例如:

    <label autofocus> </label>
    

    ---------------- 另一种解决方案 -------------------

    你可以在 javascript 中使用 blur() 方法,在视图被渲染之后。

    在 AfterViewInit 内部

    @Component({
        selector: 'my-cmp', 
        templateUrl: `my-cmp.html`
    })
    class MyComponent implements AfterViewInit {
      @ViewChild('buttonsList') buttonsList;
    
      ngAfterViewInit() {
        // execute blur on the first child of the list.
        this.buttonsList.nativeElement.firstChild.blur();
      }
    }
    

    在您的模板中:

    <div #buttonsList *ngFor='let item of items'>
        <button meta-button> {{item}} </button>
    </div>
    

    【讨论】:

    • 什么都没有改变...我尝试使用
    • 第二种解决方案也不起作用:-/我现在正在尝试通过将聚焦的背景颜色更改为与未聚焦时相同的颜色来解决它...
    • 好的,当我将聚焦的背景颜色设置为红色时,它可以工作......但是当我将它设置为颜色时,按钮会失去焦点,它只是被忽略......看起来好像材料为我决定
    猜你喜欢
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多