簡體   English   中英

在 angular 2 中單擊按鈕時如何將焦點設置到 div?

[英]How to set focus to the div when button click in angular 2?

我想在單擊按鈕時將焦點設置到頁面頂部的div 這意味着它在單擊按鈕時進行驗證,如果驗證失敗,則需要將焦點放在頁面頂部,即驗證錯誤顯示的位置。

那么如何讓頁面的頂部div獲得焦點。 表格在modal-dialog中。

如果要使不可聚焦元素成為焦點,則必須為其添加 tabindex 屬性,而div屬於該類別。

更多關於tabIndex

使用這樣的東西

<div tabindex="1"></div>

或者甚至為此制定一個指令,這將幫助您自定義功能

import { Directive, Input, ElementRef, Inject, OnChanges } from '@angular/core';

@Directive({ selector: '[focusField]' })
export class FocusDirective implements OnChanges {

  @Input('focusField') focusField: any;
  constructor(@Inject(ElementRef) private element: ElementRef) { }

  ngOnChanges(changes){
    if(changes.focusField.currentValue){
      this.element.nativeElement.focus();
    }
  }
}

您可以嘗試在組件中添加@ViewChild並使用.nativeElement.focus()

組件html:

<div #myerr class="my-error">{{myError}}</div>

組件 ts :

 export class YourComponent implements AfterViewInit {
   @ViewChild('myerr') myErrorText: ElementRef;


  ngAfterViewInit() {
    this.myErrorText.nativeElement.focus();
  }
}

您可以通過觸發函數更改 ngAfterViewInit()。 如果你願意,你可以給我你的代碼,我調整我的答案。

嘗試這樣的事情

組件.html

 <div #topElement> </div>
 <button (click)="changeFocus()"> change Focus </button>

組件.ts

export default class MyComponent {
 changeFocus() {
     window.location.hash = '#topElement';
 }
}

暫無
暫無

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

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