簡體   English   中英

專注於當前的活動元素

[英]focus on the current active element

我想關注基於其本機元素的元素。

我正在使用Angular 2, this.elem.nativeElement為我提供了所需的全部詳細信息。 但是我無法將焦點放在this.elem.nativeElement的元素之一this.elem.nativeElement

我想專注於id="dateEdit"

請幫助我。

<div class="mydp" id="dtpid">
    <div class="selectiongroup">
        <div [formGroup]="form" class="ntt">
            <input type="text" id="{{controlName}}" [formControlName]="controlName" (click)="openBtnClicked()" (blur)="changeValue($event.currentTarget.value)" class="datePickAtUnique selection form-control" [ngClass]=" 
        {'invaliddate': invalidDate&&opts.indicateInvalidDate}" placeholder=" 
        {{opts.showDateFormatPlaceholder? 
        opts.dateFormat:opts.customPlaceholderTxt}}">
        </div>
        <span id="datePickAT" class="selbtngroup" [style.height]="opts.height">
        <button type="button" id="dateEdit" aria-label="Clear Date" 
        class="btnclear" *ngIf="selectionDayTxt.length>0" 
         (click)="removeBtnClicked()" [ngClass]="{'btnclearenabled': 
       !opts.componentDisabled, 'btncleardisabled': opts.componentDisabled}" 
       [disabled]="opts.componentDisabled">
          <span class="icon icon-cross" [ngStyle]="{'line-height': 
          opts.height}"></span>
        </button>
        <button type="button" id="dateChange" aria-label="Open Calendar" class="btnpicker" (click)="openBtnClicked()" [ngClass]=" 
        {'btnpickerenabled': !opts.componentDisabled, 'btnpickerdisabled': 
         opts.componentDisabled, 'disabled': disabled}" [disabled]="opts.componentDisabled">
            <span class="icon icon-calendar" [ngStyle]="{'line-height': 
             opts.height}"></span>
        </button>
        </span>
    </div>

克里斯·特恩布爾(Chris Turnbull)提供了一個github倉庫。 這是鏈接: 通過控制器設置元素焦點的Angular指令

將此包含到您的項目中。 基本上,您要做的就是在要設置焦點的任何元素上使用ng-set-focus屬性,並為其賦予一個值(必須是唯一的)。 然后在控制器中使用$ broadcast將焦點設置在該元素上。 您必須在控制器中注入ngSetFocus服務。

例:

In dom:
    <button ng-click="setFocusHere('button1')">Button 1</button>
    <button ng-click="setFocusHere('button2')">Button 2</button>

In controller:
     <script>
  angular.module('ngSetFocusDemo', ['ngSetFocus'])
    .controller('DemoController', function($scope) {

      $scope.setFocusHere = function(el){
        console.log(el)
        $scope.$broadcast(el);
      }

    })
</script>

這里的工作示例

As my code shows, there are 2 buttons and I wanted the focus on the first button with id="dateEdit". I had said that .focus() always points to the first element with this id, it was because I was calling the .focus() before the element even loaded, for this I changed my angular 2 condition from "ngIf" to "hidden". I came up with this, that helped me,

var x = this.elem.nativeElement.getElementsByTagName("button")[0];
setTimeout(function(){
x.focus();
},100);

暫無
暫無

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

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