сосредоточиться на текущем активном элементе - PullRequest
0 голосов
/ 06 июля 2018

Я хочу сосредоточиться на элементе, основанном на его нативном элементе.

Я использую Angular 2, 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>

Ответы [ 2 ]

0 голосов
/ 13 июля 2018
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);
0 голосов
/ 06 июля 2018

Крис Тернбулл выпустил репозиторий github. Вот ссылка: Угловая директива для установки фокуса элемента через контроллер

Включите это в свой проект. По сути, вам нужно использовать атрибут 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>

Рабочий пример здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...