在单击“添加”按钮时,我想添加带有伪指令AutoFocus的输入。 自动聚焦仅在首次添加时起作用。 在我的HTML中,单击添加按钮后,只有一个输入带有指令autofocus。
这是我的指令代码:
import {Directive, ElementRef, Input, OnInit} from '@angular/core';
@Directive({
selector: '[appAutoFocus]'
})
export class AutoFocusDirective implements OnInit {
private _autofocus;
constructor(private el: ElementRef) {
}
ngOnInit() {
if (this._autofocus || typeof this._autofocus === 'undefined') {
// this.el.nativeElement.focus();
setTimeout(() => {
this.el.nativeElement.focus();
}, 500);
}
}
@Input() set autofocus(condition: boolean) {
this._autofocus = condition !== false;
}
}
我的HTML包含很多情况,但我添加了它:
<div class="tab-container">
<div class="item_key" *ngIf="addFirstParam && containersParams.length == 0">
<span class="key_span">Key</span>
<input [(ngModel)]="model.urlParams" appAutoFocus
#urlParams="ngModel"
name="urlParams"
class="add_key"
(input)="addParamsToUrl($event.target.value)">
<span (click)="deleteLastFromParamList()" class="delete_item"><i
class="icon-bin"></i></span>
</div>
<div *ngIf="urlParamsList.length > 0">
<div class="item_key" *ngFor="let container of urlParamsList; let i = index;">
<span class="key_span">Key</span>
<input value="{{container}}" class="add_key" (input)="updateParamsInUrl($event.target.value, i)">
<span (click)="deleteFromParamList(container, i)" class="delete_item"><i
class="icon-bin"></i></span>
</div>
</div>
<div *ngIf="containersParams.length > 0">
<div *ngFor="let container of containersParams">
<div class="item_key elem_{{container}}">
<span class="key_span">Key</span>
<input [(ngModel)]="model.urlParams"
#urlParams="ngModel"
name="urlParams"
class="add_key" appAutoFocus
(input)="addParamsToUrl($event.target.value)" >
<span (click)="deleteLastFromParamList()" class="delete_item"><i
class="icon-bin"></i></span>
</div>
</div>
</div>
<div (click)="addKeyRequestParams()" class="btn btn-success" *ngIf="canAdd">
<span class="for-btn icon-plus"></span>
<span i18n="@@newEndpointBtn">Key</span>
</div>
<div class="btn btn-cancel" *ngIf="!canAdd">
<span class="for-btn icon-plus"></span>
<span i18n="@@newEndpointBtn">Key</span>
</div>
</div>
如何在每次点击时激活自动对焦?