我想专注于基于其本机元素的元素。
我正在使用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>
答案 0 :(得分:0)
克里斯·特恩布尔(Chris Turnbull)提供了一个github仓库。这是链接:Angular directive to set an element focus via the controller
将此包含到您的项目中。基本上,您要做的就是在要设置焦点的任何元素上使用 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>
答案 1 :(得分:0)
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);