Это мой текущий код:
import { Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autofocus]"
})
export class AutofocusDirective
{
private focus = true;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this.focus)
{
//Otherwise Angular throws error: Expression has changed after it was checked.
window.setTimeout(() =>
{
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
});
}
}
@Input() set autofocus(condition: boolean)
{
this.focus = condition !== false;
}
}
Прецедент:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
Устаревшие код (старый ответ, на всякий случай):
Я закончил с этим кодом:
import {Directive, ElementRef, Renderer} from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class Autofocus
{
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
}
Если я поставлю код в ngOnViewInit
он не работает. Код также использует лучшие практики, так как вызов фокуса на элементе напрямую не равен recommended.
Edited (условный автофокусировка):
Несколько дней назад мне нужно было условное автофокус, потому что я скрываю первый элемент автофокусировки и я хочу сосредоточиться другим, но только тогда, когда первый не видно, и я закончил с этим код:
import { Directive, ElementRef, Renderer, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
Edited2:
Renderer.invokeElementMethod is deprecated и новый Renderer2 не поддерживает его. Итак, мы вернулись к собственному фокусу (который не работает вне DOM-SSR, например!).
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
Прецедент:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
Вторая альтернатива должна работать прямо из коробки. Это не так? – Hampus
Нет, это не так. – Makla
Просто использование «автофокусировки» не работает, потому что это действует только при загрузке страницы, а не в том случае, когда Angular меняет содержимое. – Dave